How the FormData Browser API works

Christian Nwamba

The FormData web API object represents HTML form data. It provides a way to easily store key-value pairs in relation to HTML form fields and values. In this article, we’ll discuss syntax, FormData API methods, usage, and some examples.

FormData Syntax

The syntax for creating a FormData object is:

1//javascript
2const formData = new FormData() //this creates an empty formData object

The FormData() accepts one argument; an HTML form element.

When you should use FormData

The only time you would need to use FormData is when you’re sending data to a server via a POST request.

The FormData object has some very useful methods. In this section, we’ll look at some of them.

  • .append(name, value, filename): adds a value to an existing key in an object
    • example: formData.append('first_name', 'Sammy');
  • .delete(name): removes a key/value pair from the FormData object. it accepts the key or name of the key as argument.
    • example: formData.delete('first_name')
  • .entries(): returns an iterator that loops through the FormData object entries to get the list of key/value pairs.
    • example
1//JavaScript
2const formData = new FormData()
3formData.append('first_name', 'Sammy');
4formData.append('nick_name', 'Honey Badger');
5
6for(const entry of formData.entries()) {
7 console.log(`${entry[0]}, ${entry[1]}`);
8}
9
10// Results
11
12// first_name, Sammy
13// nick_name, Honey Badger
  • .get(name): returns the first value of a key in the FormData object.
    • example
1//JavaScript
2formData.get('nick_name')
3//returns 'Honey Badger'
  • .getAll(name): returns an array of all the values associated with a key.
    • example
1//JavaScript
2formData.append('last_name', 'Messi');
3formData.append('last_name', 'Ronaldo');
4
5formData.getAll('last_name')
6
7// RESULT
8
9// ['Messi', 'Ronaldo']
  • .has(name): returns a boolean value if the FormData object has a certain key.
    • example
1//JavaScript
2formData.has('other_name') // false
  • .keys(): returns an iterator that loops through all the keys contained in the FormData object.
    • example
1//JavaScript
2for (const key of formData.keys()) {
3 console.log(key);
4}
5
6// first_name
7// last_name
8// nick_name
  • .set(name, value, filename): adds a new value to an existing key. If the key/value doesn’t exist, it adds them. The filename argument is optional
    • example
1//JavaScript
2formData.set('last_name', 'Fati');
3formData.get('last_name'); // "Fati"
  • .values: returns an iterator that loops through all the values contained in the FormData object.
    • example
1//JavaScript
2
3for (const value of formData.values()) {
4 console.log(value);
5}
6
7// Sammy
8// Honey Badger
9// Fati
10// Messi
11// Ronaldo

Now we know the methods FormData provides us, let’s go through some real-world samples.

Populating data from an HTML form

Let’s see how FormData works with HTML forms. In this example we would display the key/value of the HTML inputs in a list format.

Let’s see how FormData works with HTML forms. In this example we would display the key/value of the HTML inputs in a list format. The demo is here on Codesandbox.

1<!--HTML --!>
2<form id="form">
3 <input type="text" name="first_name" value="Sammy">
4 <input type="text" name="nick_name" value="Honey Badger">
5 <input type="password" name="password" value="password123">
6</form>
7
8<pre id="output"></pre>
1//JavaScript
2const form = document.getElementById("form");
3const formData = new FormData(form)
4 const output = document.getElementById("output")
5
6for (const [key, value] of formData) {
7 output.textContent = output.textContent + `${key}: ${value}\\n`;
8}

Sending input data to a server

Let’s work on a more realistic example.

1//JavaScript
2const submit = async () => {
3 try {
4 const formData = new FormData
5 formData.append('myFileData', document[0])
6 let response = await fetch('/upload', {
7 method: 'POST',
8 body: formData,
9 headers: {
10 'Content-type': 'application/json; charset=UTF-8',
11 },
12 });
13 const result = await response.json();
14
15 showMessage(result.message, response.status == 200 ? 'success' : 'error');
16
17 } catch (error) {
18 showMessage(error.message, 'error');
19 }

Here, we are uploading a file to the upload API endpoint. You can see how we made use of the formData.append() method to add the filename as value to the myFileData key.

Conclusion

The FormData web API object is constructed from the FormData Interface. The interface enables us to create key/value pairs to represent our HTML form field values. In this article, we mentioned that the only time you will need to use the FormData object is when you’re sending data to a server. We also outlined the FormData methods with appropriate examples and worked on some realistic examples where FormData was used.

Further Reading

Christian Nwamba

Developer Advocate at AWS

A software engineer and developer advocate. I love to research and talk about web technologies and how to delight customers with them.