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

3

49

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()?

Achernar answered 2/11, 2015 at 2:8 Comment(0)
N
47

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

Nitrobenzene answered 2/11, 2015 at 2:15 Comment(0)
E
8

One more important difference is the treatment of empty input-fields in forms.

serialize()
only contains input-fields with a value. Unchecked check-boxes or empty input-fields will be missing in the key/value pairs. Therefore the backend of your application will have to do some book-keeping in order to interpret missing keys as empty values.
FormData
will get you a complete list of all your form fields and their values. Even if they are empty.
Eightieth answered 9/1, 2018 at 11:49 Comment(0)
S
0

When sending data through an AJAX call, two options are commonly used: FormData and serialize(). While both methods have limitations, they serve different purposes:

  • FormData:
    • Allows sending selected files along with other field values.
    • Limitation: Excludes textarea content.
  • serialize():
    • Can capture all data values, including textarea contents.
    • Limitation: Excludes selected files.

In summary, FormData is ideal for sending files, while serialize() is better suited for sending text data, including textarea values.

Supervision answered 4/7 at 18:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.