7

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 ?

1

3 Answers 3

17

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

});
Sign up to request clarification or add additional context in comments.

Comments

0

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
});

Comments

-1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.