12

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?

2
  • @Esailija I need to get the contents of the form including FILES to post with ajax, didn't think serialize() could handle files? Commented Jun 26, 2012 at 13:39
  • I was confused because you said "array". I edited it to be what I think you are asking. Commented Jun 26, 2012 at 13:40

5 Answers 5

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

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

Sign up to request clarification or add additional context in comments.

Comments

2

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)
});​

Comments

2

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);

Comments

1
$( '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();

});

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.