How to combine two javascript FormData objects

I need to combine two FormData objects and publish them using XMLHttpRequest. One of the forms contains an input file.

var formData = new FormData(document.forms.namedItem('form-ship')); var poData = new FormData(document.forms.namedItem('po-form')); // Combine them var fData = $.extend(true, formData, poData); 

This does not work when I use $.extend or use serialize() to combine a form in which there is no file input. Any idea how to do this?

+8
source share
3 answers

You can not. FormData , FormData not listed.

However, as you say, only one of your forms contains an input file. Then you should use serializeArray on another and append for the data manually:

 var formData = new FormData(document.forms['form-ship']); // with the file input var poData = jQuery(document.forms['po-form']).serializeArray(); for (var i=0; i<poData.length; i++) formData.append(poData[i].name, poData[i].value); 
+7
source

I did it as follows:

 let formData = new FormData($("#f_articulos")[0]); let formDataPrecios = new FormData($("#f_listado_precios")[0]); for (var pair of formDataPrecios.entries()) { formData.append(pair[0], pair[1]); } 
+1
source

You can serialize forms and merge them into an array:

 var fd1 = $(document.forms['form-id-1']).serializeArray(); var fd2 = $(document.forms['form-id-2']).serializeArray(); var fd = $.merge(fd1, fd2); 

Click to Download Jquery SerializeArray Documentation

Click on the JQuery Documentation Merge Page

0
source

All Articles