How do I POST an array of objects with $.ajax (jQuery or Zepto) How do I POST an array of objects with $.ajax (jQuery or Zepto) jquery jquery

How do I POST an array of objects with $.ajax (jQuery or Zepto)


Be sure to stringify before sending. I leaned on the libraries too much and thought they would encode properly based on the contentType I was posting, but they do not seem to.

Works:

$.ajax({    url: _saveAllDevicesUrl,   type: 'POST',   contentType: 'application/json',   data: JSON.stringify(postData) //stringify is important,   success: _madeSave.bind(this)});

I prefer this method to using a plugin like $.toJSON, although that does accomplish the same thing.


Try the following:

$.ajax({  url: _saveDeviceUrl, type: 'POST', contentType: 'application/json', dataType: 'json', data: {'myArray': postData}, success: _madeSave.bind(this)//, processData: false //Doesn't help});


edit: I guess it's now starting to be safe to use the native JSON.stringify() method, supported by most browsers (yes, even IE8+ if you're wondering).

As simple as:

JSON.stringify(yourData)

You should encode you data in JSON before sending it, you can't just send an object like this as POST data.

I recommand using the jQuery json plugin to do so. You can then use something like this in jQuery:

$.post(_saveDeviceUrl, {    data : $.toJSON(postData)}, function(response){    //Process your response here});