Search code examples
jqueryajaxform-data

partial form data submission with FormData api


With Ajax it is possible to send partial data for form using below as data for ajax-

$("#CreateForm").find("#form-section-1").find('input, textarea, select').serialize()

Trying same with FormData api -

new FormData($('form#CreateForm')[0])

This does not work however -

var formdata = new FormData($('form#CreateForm').find("#form-section-1").find('input, textarea, select'))

Since below loop gives no result -

for (var pair of formdata.entries()) {
    console.log(pair[0]+ ', ' + pair[1]); 
}

How can partial form data be submitted with FormData api in compact form like serialize ?

Edit: In Accepted solution, I had to further add this condition for files especially -

if($(this).is(':input:file')) { 
formData.append(this.name, $(this)[0].files[0]); 
} else { 
formData.append(this.name, $(this).val()); 
}

Solution

  • The FormData constructor accepts an optional native <form/> element parameter to pass all of the data in the form. Notice,

    $('form#CreateForm') // jQuery object
    $('form#CreateForm')[0] // native form element
    $('form#CreateForm #form-section-1').find('input, textarea, select') // jQuery objects
    $('form#CreateForm #form-section-1').find('input, textarea, select')[0] // some native non-form element 
    

    So you can't really use the constructor.

    The FormData object does have an .append method to add new values into the object. You could use it to do

    var formData = new FormData();
    $('form#CreateForm #form-section-1').find('input, textarea, select').each(function () {
            if($(this).is(':input:file')) {
                formData.append(this.name, $(this)[0].files[0]);
            } else {
                formData.append(this.name, $(this).val());
            }
    });
    

    FYI :input is shorthand for input|select|textarea|button.