How to pass parameters in $ajax POST?
I have followed the tutorial as stated in this link. In the code below for some reason the data is not appended to the url as parameters, but if I set them directly to the url using /?field1="hello"
it works.
$.ajax({
url: 'superman',
type: 'POST',
data: { field1: "hello", field2 : "hello2"} ,
contentType: 'application/json; charset=utf-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
I would recommend you to make use of the $.post
or $.get
syntax of jQuery for simple cases:
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
});
If you need to catch the fail cases, just do this:
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
}).fail(function(){
console.log("error");
});
Additionally, if you always send a JSON string, you can use $.getJSON or $.post with one more parameter at the very end.
$.post('superman', { field1: "hello", field2 : "hello2"},
function(returnedData){
console.log(returnedData);
}, 'json');
Jquery.ajax does not encode POST data for you automatically the way that it does for GET data. Jquery expects your data to be pre-formated to append to the request body to be sent directly across the wire.
A solution is to use the jQuery.param function to build a query string that most scripts that process POST requests expect.
$.ajax({
url: 'superman',
type: 'POST',
data: jQuery.param({ field1: "hello", field2 : "hello2"}) ,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
In this case the param
method formats the data to:
field1=hello&field2=hello2
The Jquery.ajax documentation says that there is a flag called processData
that controls whether this encoding is done automatically or not. The documentation says that it defaults to true
, but that is not the behavior I observe when POST
is used.
Try using GET method,
var request = $.ajax({
url: 'url',
type: 'GET',
data: { field1: "hello", field2 : "hello2"} ,
contentType: 'application/json; charset=utf-8'
});
request.done(function(data) {
// your success code here
});
request.fail(function(jqXHR, textStatus) {
// your failure code here
});
You cannot see parameters in URL with POST method.
Edit:
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.