Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting array using formdata

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.

like image 369
Rainer Sauerstoff Avatar asked Jun 07 '12 18:06

Rainer Sauerstoff


4 Answers

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);
});
like image 82
Matt Stapleton Avatar answered Nov 01 '22 13:11

Matt Stapleton


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']);
                }
like image 39
Rainer Sauerstoff Avatar answered Nov 01 '22 14:11

Rainer Sauerstoff


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

like image 3
Bill Avatar answered Nov 01 '22 13:11

Bill


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 }));
like image 2
codegrid Avatar answered Nov 01 '22 15:11

codegrid