I have the following code:
$.ajax({
method: "POST",
url: "/handler",
contentType: "application/json",
data: data_all,
})
.done(function(r) { ...stuff... })
.fail(function(r) { ...stuff... });
data_all
is a dictionary (e.g., {"a":1, "b":2}
). Running this code currently returns a 400 error (using django, in case relevant). If I make one change:
...
data: JSON.stringify(data_all),
...
It all works.
The thing is, that shouldn't be the case. The jQuery AJAX docs clearly states that the data
argument accepts strings, arrays, and PlainObjects. When in debugger mode (using Chrome dev tools), I have verified that data_all
is a PlainObject:
jQuery.isPlainObject(data_all) # returns "true"
I'm using jQuery 2.1.4, so this should be there. Any idea why this requires the stringify
function?
To send json data with jquery, you must stringify the object before passing it to jQuery; jQuery will not do it for you.
Under the hood, If the processData parameter is true (it is by default) and the data parameter doesn't contain a string, the value of the data parameter is passed to $.param()
which creates a param string. Therefore, if you pass an object to the data param, your request body will contain a=1&b=2
. If you simply set processData to false, jquery will skip the $.param
process and directly send the .toString value of your object to the request body, which is [object Object]
, so that's not going to work either. If you stringify the object to JSON, it will be a string and jQuery will pass it through unchanged to the request body.