Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two javascript FormData objects

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

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

It doesn't work when I use $.extend or if I use serialize() to combine the form that doesn't have file input. Any idea how to do this?

like image 704
u54r Avatar asked Mar 14 '14 15:03

u54r


2 Answers

I did it this way:

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]);
}
like image 154
andreshg112 Avatar answered Oct 15 '22 04:10

andreshg112


You cannot couldn't. FormData is was unfortunately not enumerable.

However, as you say only one of your forms does contain a file input. Then it should be possible to use serializeArray on the other and append to 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);
like image 33
Bergi Avatar answered Oct 15 '22 04:10

Bergi