I\'d like to POST an array of objects with $.ajax in Zepto or Jquery. Both exhibit the same odd error, but I can\'t find what I\'m doing wrong.
The data saves to the
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
});
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.
I was having same issue when I was receiving array of objects in django sent by ajax. JSONStringyfy worked for me. You can have a look for this.
First I stringify the data as
var myData = [];
allData.forEach((x, index) => {
// console.log(index);
myData.push(JSON.stringify({
"product_id" : x.product_id,
"product" : x.product,
"url" : x.url,
"image_url" : x.image_url,
"price" : x.price,
"source": x.source
}))
})
Then I sent it like
$.ajax({
url: '{% url "url_name" %}',
method: "POST",
data: {
'csrfmiddlewaretoken': '{{ csrf_token }}',
'queryset[]': myData
},
success: (res) => {
// success post work here.
}
})
And received as :
list_of_json = request.POST.getlist("queryset[]", [])
list_of_json = [ json.loads(item) for item in list_of_json ]
Check this example of post the array of different types
function PostArray() {
var myObj = [
{ 'fstName': 'name 1', 'lastName': 'last name 1', 'age': 32 }
, { 'fstName': 'name 2', 'lastName': 'last name 1', 'age': 33 }
];
var postData = JSON.stringify({ lst: myObj });
console.log(postData);
$.ajax({
type: "POST",
url: urlWebMethods + "/getNames",
data: postData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (msg) {
alert(msg.d);
}
});
}
If using a WebMethod in C# you can retrieve the data like this
[WebMethod]
public static string getNames(IEnumerable<object> lst)
{
string names = "";
try
{
foreach (object item in lst)
{
Type myType = item.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
foreach (PropertyInfo prop in props)
{
if(prop.Name == "Values")
{
Dictionary<string, object> dic = item as Dictionary<string, object>;
names += dic["fstName"];
}
}
}
}
catch (Exception ex)
{
names = "-1";
}
return names;
}
Example in POST an array of objects with $.ajax to C# WebMethod
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
}
);