Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery : How to send JSON data in AJAX post?

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 ?

like image 516
Pracede Avatar asked Jul 10 '18 16:07

Pracede


People also ask

How do I send a POST request with JSON payload?

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.

How pass JSON data to ajax to controller?

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.

How use jQuery ajax post method?

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.


1 Answers

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

});
like image 154
Ahmad Avatar answered Oct 22 '22 07:10

Ahmad