I am having trouble sending a JavaScript objects over a http request. The http endpoing only accepts json content-type (“application/json” or “text/json”)
I am not sure why
data2 ( stringified json ) works fine
But, data1 ( json object ) throws http 400 Bad Request.
i.e why is jQuery not serializing the json object to a valid json string for the server to process.
var data1 = ({ rating : 3 }); //does not work
var data2 = '{ "rating" : 3}'; //works fine
$.ajax({
url : "/rate",
data : data1,
type : "POST",
contentType: "application/json",
success: function(json){
console.log("Ajax Return :"+json);
}
});
By default data parameter values that is part of any ajax jQuery call, converts the JS object into a url-form-encoding i.e “param1=value¶m2=value” string. This is the case for both GET and POST requests.
Interestingly, even if you explicitly specify { contentType : “application/json” } in the ajax method call, only the appropriate header is set, the JS object you pass as value for the data parameter is not converted to a JSON string ( one always hopes for more intelligence ), but still gets encoded as url-form-encoding. So, one has to explicitly convert the JS object to JSON string.
There are a options for doing so,
So, now my POST request that needs a json body would work like this.
Note:
Effect of “processData” boolean parameter
Some answer here mentioned that one has to set { processData : false }. But, this is not the case. This has an effect only when the type of “data” parameter is not a string. If its not a string then the default behavior is to convert the Object into url-form-encoding. But, this is mostly useless I think because if you pass a regular Object and processData is set to false, then it tries to do (data).toString which results in “[Object] [Object]” which is pretty useless.