Solved. The solution is to set contentType to 'application/json' and use the JSON.stringify(obj) instead of obj, but you may then have to change how you get the data on your server, depending on the language or framework. Original question below...
Here's what I'm trying
var obj = {
'firstName': 'bill',
'lastName': 'johnson',
'hobbies': ['apples', 'dogs']
});
$.ajax({
type: 'POST',
url: '/myurl'
data: obj,
success: function(data){alert(data);}
});
If I alert/log a JSON.stringify(obj)
, I get the correct result, i.e.:
{'firstName': 'bill', 'lastName': 'johnson', 'hobbies': ['apples', 'dogs']}
However, when I do the above ajax call, my server gets the following:
{'firstName': 'bill', 'lastName': 'johnson', 'hobbies[]': 'apples'}
Which clearly is not proper json. I've tried adding various contentType
arguments but then my server actually gets nothing (an empty post request).
I also tried setting the data argument to a pre-stringified string of JSON (which is correct), but then jquery escapes it and my server gets this:
{"{\"firstName\":\"bill\",\"lastName\":\"johnson\",\"hobbies\":[\"apples\",\"dogs\"]}": ""}
I tried setting processData
to false
and that changes nothing.
I've researched this for hours and haven't gotten it to work. Surely there's a way to send json with lists to the server...
any tips?