Posting an array using formdata

I am using the new HTML5 FormData-Object to publish some values ​​and images via Ajax. While this is working. Now I want to publish the array using this object, but all I got on the server side is "[object-object]". How to send an array using formdata?

What i still have

var formData=new FormData(); formData.append('text', $('#text').attr('value')); formData.append('headline',$('#headline').attr('value')); formData.append('myarray',{key1: 'bla', key2: 'blubb'}); 

The last line does not work. I am sending a request using this code

  $.ajax({ url: 'xyz', data: formData, type: 'POST', processData: false, contentType: false, success: function(data) { var decoded=$.parseJSON(data); displaySuccess('Success', decoded.message); },error: function(data){ var decoded=$.parseJSON(data); displayError('Error', decoded.message); },complete: function(data){ $('#cursor').hide(); $("#submitbutton").removeAttr('disabled') } }); 

Thanks in advance.

+8
jquery arrays post html5 image
source share
4 answers

From your syntax, you are trying to pass an object, not an array. I don’t think you can pass objects through an HTML form.

 { key1 : value1 , key2 : value2 } 

against

 [ value1, value2 ] 

This is a handy reference to the general JS syntax.

+3
source share

Using .append() for each element of an associative array can produce the expected results.

Instead of this line:

 formData.append('myarray',{key1: 'bla', key2: 'blubb'}); 

You can try the following:

 var myarray = {key1: 'bla', key2: 'blubb'}; jQuery.each(myarray, function(key, value) { formData.append('myarray['+key+']', value); }); 
+15
source share

Thanks. Now I came up with this solution:

  for (i = 0; i < social_networks.length; i++) { formData.append("myarray["+i+"][mykey]",arr[i]['mykey']); formData.append("myarray["+i+"][mykey2]",arr[i]['mykey2']); } 
+4
source share

Try it. It worked for me.

 var files = $scope.myFile; var fd = new FormData(); fd.append("file", files[0]); fd.append("assignment", JSON.stringify({ classAssignment: $scope.editItem })); 
+2
source share

All Articles