Dan
Dan

Reputation: 12096

How to add an array value to new FormData?

On form submission I'm using jQuery to gather data including files and creating a FormData Object of the form values using:

var formData = new FormData($("form#formid")[0]);

but how can I add another value and it's key to this FormData Object?

Upvotes: 12

Views: 33742

Answers (5)

Lucky
Lucky

Reputation: 17345

You can also use FormData.set().

The difference between FormData.set and append() is that if the specified key already exists, FormData.set will overwrite all existing values with the new one, whereas append() will append the new value onto the end of the existing set of values.

Syntax:

formData.set(name, value);

Upvotes: 2

Alex
Alex

Reputation: 161

var data = new FormData(),
    fields = $("#myForm").serializeArray();

$.each( fields, function( i, field ) {
    data.append(field.name, field.value);
});

Upvotes: 1

Tony
Tony

Reputation: 91

$( 'form' ).submit(function ( e ) {
var data;

data = new FormData();
data.append( 'file', $( '#file' )[0].files[0] );

$.ajax({
    url: 'http://hacheck.tel.fer.hr/xml.pl',
    data: data,
    processData: false,
    type: 'POST',
    success: function ( data ) {
        alert( data );
    }
});

e.preventDefault();

});

Upvotes: 1

Calvein
Calvein

Reputation: 2121

You can iterate over all the fields in the form and add them to the FormData quite easily this way :

var formData = new FormData();
$("form#edit-account").serializeArray().forEach(function(field) {
  formData.append(field.name, field.value)
});​

Upvotes: 2

Esailija
Esailija

Reputation: 140210

var formData = new FormData($("form#formid")[0]);
formData.append("key", "value")

See https://developer.mozilla.org/en/XMLHttpRequest/FormData

Upvotes: 22

Related Questions