MVC4 Ajax call using Jquery, should it be Post or Get?
Solution 1
Regarding the POST vs GET dilemma, this is a question of design, not availability. As you know, jQuery allows you to issue both POST and GET requests.
I list some connotations of using GET request:
- Server's response to GET request may get cached by the browser, so don't use GET if you may return different content on subsequent request.
- According to HTTP spec, GET request shouldn't cause any side-effect on the server side.
- All the information you transmit via GET request is encoded as a part of URL. Be prepared that this URL may be accessed from somewhere else (like another website, forum, or by a web crawler).
- Because of the above, with GET you don't have any reliable means of protecting from cross-site request forgery.
- By default, ASP.NET MVC prohibits the server from responding to AJAX GET requests.You can disable this behavior (see this question for code sample).
- Browsers (and sometimes servers) impose limitations on the length of the URL. As a rule of thumb, 2000 characters is safe. (see this question for details).
This question gives more information on the topic, and so does Wikipedia on HTTP protocol.
If you are not sure that your AJAX API satisfies the requirements for GET requests, use POST.
Solution 2
use $.ajax
var fruit = 'Banana';
$.ajax({
url: ajaxurl,//your url
type"'POST',//also can set GET
data: {//passing parameter
'action':'example_ajax_request',
'fruit' : fruit
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
Toubi
Updated on June 04, 2022Comments
-
Toubi almost 2 years
In a application I m using Jquery with MVC4 and I need to query data on server. I understand JQuery provide multiple methods for Ajax request but I m not getting which particular method I should use ?
I will pass parameter and receive some data and also in case of request failure or timeout I need to do something. Please advice which method I should go with.
Cheers
-
Sang Suantak over 10 yearsMaybe this will help stackoverflow.com/questions/46585/…
-
-
Toubi over 10 yearsThanks @Sumit Chourasia, using post can I not receive data back from server to my page ? and using get can I pass parameter as well ?
-
Toubi over 10 yearsthanks @Péter, can you please guide a little more what do you mean by data change in request ? Using get method can I pass parameter to server method as well ?
-
Toubi over 10 yearsthanks @Rituraj ratan using post can I get data back on server as well ? and using get can I pass parameter to server ?
-
Sumit Chourasia over 10 yearswell, you can do things that way also, but it will raise some security issues, and it is not a good practice to use that way.
-
Rituraj ratan over 10 yearsyes @Toubi you can get see api.jquery.com/jQuery.ajax for more detail it will helpfull for you