Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormData vs jQuery#serialize(), What is the difference?

Recently I was submitting a form using AJAX.

In researching the best method I saw some AJAX submissions using jQuery#serialize() and others using FormData. For example.

One submission did this:

data: $('form').serialize() 

while the other did:

var formData = new FormData($('form')[0]); data: formData 

So what is the difference between FormData and jQuery#serialize()?

like image 359
L84 Avatar asked Nov 02 '15 02:11

L84


People also ask

What is FormData () in jQuery?

The jQuery Ajax formData is a method to provide form values like text, number, images, and files and upload on the URL sever. The jQuery Ajax formData is a function to create a new object and send multiple files using this object.

What is FormData?

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the fetch() or XMLHttpRequest. send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data" .

What is the use of FormData in Javascript?

The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest . It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data.

How do I serialize FormData?

To serialize a FormData object into a query string, pass it into the new URLSearchParams() constructor. This will create a URLSearchParams object of encoded query string values. Then, call the URLSearchParams. toString() method on it to convert it into a query string.


1 Answers

The main difference from a usage standpoint is that you can't serialize files, only file names....the value of a file input.

FormData object on the other hand also includes files if applicable.

Also serialize() will work in older browsers that don't support the FormData API for example IE < 10

reference FormData docs

like image 89
charlietfl Avatar answered Oct 09 '22 04:10

charlietfl