I am using the new HTML5 FormData-Object to post some values and an image via Ajax. It works fine so far. Now, I want to post an array using this object, but all I´ve got on server-side is "[object - object]". How can I post an array with formdata?
What I´ve got so far
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 doesn´t work. I send the request with 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.
Using .append() on each element of the associative array might produce the results you're expecting.
In place of this line:
formData.append('myarray',{key1: 'bla', key2: 'blubb'});
You might try the following:
var myarray = {key1: 'bla', key2: 'blubb'};
jQuery.each(myarray, function(key, value) {
    formData.append('myarray['+key+']', value);
});
                        Thanks. I now 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']);
                }
                        From your syntax, you appear to be trying to pass an object, not an array. I don't think you can pass objects through HTML form.
{ key1 : value1 , key2 : value2 }
vs
[ value1, value2 ]
This is a handy reference to general JS syntax
Try this. 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 }));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With