Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always call JSON.stringify on post data for jQuery Ajax

Tags:

jquery

ajax

Or any other function to preprocess your data for that matter :)

Because of my server side framework, I always need to call JSON.stringify before sending my data - unnecessary boilerplate, that you can forget to add.

Right now I have:

$.ajax({     [...]     data: JSON.stringify({ someData: self.someData }),     [...] }); 

I would prefer:

$.ajax({     [...]     data: { someData: self.someData },     [...] }); 

I've looked into ajaxSetup, but can't find a solution for this, so far...

Update

For a reason why I need this, see the following this question. I could fix this on the serverside, but for now I'm looking for a way to fix this on the clientside.

like image 601
Dirk Boer Avatar asked Jun 20 '13 14:06

Dirk Boer


2 Answers

No, there is no built-in way to pre-process your data from an object to JSON. However, you can use ajaxSetup and a beforeSend to do it for you.

$.ajaxSetup({     beforeSend: function(jqXHR,options){         if ( options.contentType == "application/json" && typeof options.data != "string" ) {             options.data = JSON.stringify(options.data);         }     } }); 

Now just make sure to set your contentType to application/json on requests that need to send json to the server so that it will get caught by the if statement.

like image 76
Kevin B Avatar answered Sep 28 '22 03:09

Kevin B


Here an alternative approach that uses a jQuery.prefilter:

$.ajaxPrefilter("json", function(options, originalOptions) {   options.data = JSON.stringify(originalOptions.data || null);   options.contentType = "application/json" // content type of *request* });  $.ajax({   data: {foo: [1,2,3]},   dataType: "json" // expected content type of *response* (must match prefilter, above!)   [...] }); 

Because prefilters match on the dataType option, we have to set it manually in our $.ajax request. If the dataType matches the prefilter ("json") then before the request is sent, it will convert the data object to a string, and set the contentType header to match ("application/json").

Keep in mind that this a a global change that will impact ALL future $.ajax requests with dataType: "json"!

like image 23
nathanallen Avatar answered Sep 28 '22 05:09

nathanallen