In JavaScript, a FormData
object is a common way to create a bundle of data to send to the server using XMLHttpRequest
or fetch.
It replicates the functionality of the
We can think of it as an array of arrays. There is one array for each element that we want to send to the server.
Each element consists of the following three things:
name
: The name of the field.
value
: The value of the field. It can be a String
or
filename
: The file’s name to be saved on the server when a Blob is passed as the second parameter.
const formData = new FormData([form]);
The formData
constructor creates and returns a new FormData
object.
If an HTML form element is provided, it automatically captures its fields. This parameter is optional.
Additional data can be added in the FormData
object using the formData.append()
method.
formData.append(name, value, filename);
FormData
object with an HTML formWe have created an HTML form that has two input fields for name
and age
respectively. Then we have created an onSubmit
function of this form.
In that function, we pass the id
of the form element to the FormData
constructor. It returns an object consisting of the data filled in the HTML form as name-value pairs.
FormData
object without an HTML form.We created a FormData
object using an empty FormData
constructor. Then, we added some data in the form of name-value pairs using the append()
method.
A FormData
object is simply an array-like iterable structure that holds many name-value pairs or potentially an HTML form.