user3587180
user3587180

Reputation: 1397

How to convert a jquery form object to FormData?

I'm getting a jquery object like this

var form = $("#form1");

How do I convert that to FormData object? Do I have to get the html out of the jquery form and then loop through all the input types and do it or is there a more robust way of doing it?

Upvotes: 1

Views: 355

Answers (3)

Dimos Double
Dimos Double

Reputation: 1

It's easy. You just need using the default constructor of FormData.

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

The code above can fetch what you want.

Upvotes: 0

Jairo Malanay
Jairo Malanay

Reputation: 1347

var formData = new FormData($('form')[0]); // Create an arbitrary FormData instance

jQuery.ajax('/endpoint.php', {
    processData: false,
    contentType: false,
    data: formData
});

refer to mattlunn blogs for more details

Upvotes: 2

Manas
Manas

Reputation: 3330

you can do it like this:

var data = $('#form').serializeArray().reduce(function(obj, item) {
obj[item.name] = item.value;
return obj;
}, {});

Upvotes: 0

Related Questions