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()
?
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.
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" .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With