How to send JSON instead of a query string with $.ajax?

JavascriptJqueryJsonQuery String

Javascript Problem Overview


Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?

$.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 query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.

Javascript Solutions


Solution 1 - Javascript

You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType 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.

Solution 2 - Javascript

No, the dataType option is for parsing the received data.

To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.

Solution 3 - Javascript

While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!

Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:

 var data = {USER : localProfile,  
	    INSTANCE : "HTHACKNEY",  
		PAGE : $('select[name="PAGE"]').val(), 
		TITLE : $("input[name='TITLE']").val(), 
		HTML : html,
		STARTDATE : $("input[name='STARTDATE']").val(), 
		ENDDATE : $("input[name='ENDDATE']").val(),
		ARCHIVE : $("input[name='ARCHIVE']").val(), 
		ACTIVE : $("input[name='ACTIVE']").val(), 
		URGENT : $("input[name='URGENT']").val(), 
	    AUTHLST :  authStr};
		//console.log(data);
	   $.ajax({
		    type: "POST",
           url:   "http://www.domian.com/webservicepgm?callback=?",
           data:  data,
		   dataType:'jsonp'
	   }).
	   done(function(data){
         //handle data.WHATEVER
       });

Solution 4 - Javascript

If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"

Original post here

Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRedsandroView Question on Stackoverflow
Solution 1 - JavascriptmekwallView Answer on Stackoverflow
Solution 2 - JavascriptBergiView Answer on Stackoverflow
Solution 3 - Javascriptyardpenalty.comView Answer on Stackoverflow
Solution 4 - JavascriptTodView Answer on Stackoverflow