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 ?
To send the JSON with payload to the REST API endpoint, you need to enclose the JSON data in the body of the HTTP request and indicate the data type of the request body with the "Content-Type: application/json" request header.
Create target "JSON object Mapper" object class file according to the business requirements. Create a "Controllers\HomeController. cs" file with default Index method and GetData(...) method with string type input query parameters for Ajax call with following lines of code i.e.
jQuery $.post() Method The $.post() method requests data from the server using an HTTP POST request. Syntax: $.post(URL,data,callback); The required URL parameter specifies the URL you wish to request.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With