Reputation: 4361
I am working on AJAX. I create a post request like the following :
$.ajax({
'url':'http://localhost/api/create/',
'method':'POST',
'dataType': 'json',
'contentType': 'application/json',
'data':{
"refId":585,
"phone":"0674444444"
},
'success': getHandlingStatus
});
When my request is executed, data are passed as parameters in my request payload and not as JSON data. Here is my Request Payload:
refId=585&phone=0674444444
I want to send data in json format like :
{
"refId":"585",
"phone:"0674444444"
}
What am I missing please ?
Upvotes: 7
Views: 29226
Reputation: 887
You need to use JSON.stringify to convert data to JSON along with ProcessData option set to false. As per documentation of jquery:
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
$.ajax({
'url':'http://localhost/api/create/',
'method':'POST',
'dataType': 'json',
processData: false,
'contentType': 'application/json',
'data':JSON.stringify({
"refId":585,
"phone":"0674444444"
}),
'success': getHandlingStatus
});
Upvotes: 17
Reputation:
You need to use JSON.stringify()
to convert the data to JSON
format. See the documentation.
$.ajax({
'url':'http://localhost/api/create/',
'method':'POST',
'dataType': 'json',
'contentType': 'application/json',
'data':JSON.stringify({
"refId":585,
"phone":"0674444444"
}),
'success': getHandlingStatus
});
Upvotes: 0
Reputation: 331
Have you tried the following
$.ajax({ 'url':'http://localhost/api/create/', 'method':'POST', 'dataType': 'json', 'contentType': 'application/json', 'data': JSON.stringify({ "refId":585, "phone":"0674444444" }), 'processData': false, 'success': getHandlingStatus });
There was a comma missing after processData: false
Upvotes: -1