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,
- JSON.stringify(obj); Its part of Javascript, I believe comes comes from ECMA 5 standard. Easiest, but the down side is it does not work in older browsers IE6 and before.
- jQuery json plugin that also has some additional features.
- Code from json.org
So, now my POST request that needs a json body would work like this.
var dataStr = JSON.stringify({ rating : 3 });
$.ajax({
url : "/rate",
data : dataStr,
type : "POST",
contentType: "application/json",
success: function(json){
console.log("Ajax Return :"+json);
}
});
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.