Dirk Boer Dirk Boer - 3 months ago 42
jQuery Question

Always call JSON.stringify on post data for 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.

Answer

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.