Redsandro Redsandro - 3 months ago 17
Javascript Question

jQuery ajax, how to send JSON instead of QueryString

Can someone explain in an easy way how to make

jQuery
send actual
json
in stead of a
querystring
?

$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});


This will in fact convert your carefully prepared
json
to a
querystring
. One of the annoying things is that any
array: []
in your object will be converted to
array[]: []
, probably because of limitations of the
querysting
.

-update-

The proper method can be found in the answers below:

$.ajax({
url : url,
dataType : 'json',
contentType: 'application/json; charset=UTF-8', // This is the money shot
data : data,
type : 'POST',
complete : callback // etc
});


Please note that this requires proper CORS headers server-side, and contrary to some examples on the net, Allow-Headers cannot use wildcards. (Allow-Origin can.)

{
Content-Type : 'application/json',
Access-Control-Allow-Origin : '*',
Access-Control-Allow-Headers : 'Content-Type' // You cannot use '*'
}


-update-

Please note that
jQuery
will now send TWO requests, one to complete the handshake and one with the actual content. This is for your own security, somehow.

So keep in mind if you want your server to be versatile, using a QueryString sends only one request. Using true JSON sends at least two requests, one for the handshake.

This was messing with my head, so I thought I'd let you (the potential reader) know in advance.

Answer

You need to use JSON.stringify to first serialize your object to JSON, and then specify the content-type so your server understands it's JSON. This should do the trick:

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    contentType: "application/json",
    complete: callback
});

Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.

Comments