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.
The syntax for creating a FormData object is:
//javascript
const formData = new FormData() //this creates an empty formData object
Code language: JavaScript (javascript)
The FormData()
accepts one argument; an HTML form
element.
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');
- example:
-
.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')
- example:
-
.entries()
: returns an iterator that loops through the FormData object entries to get the list of key/value pairs.- example
//JavaScript
const formData = new FormData()
formData.append('first_name', 'Sammy');
formData.append('nick_name', 'Honey Badger');
for(const entry of formData.entries()) {
console.log(`${entry[0]}, ${entry[1]}`);
}
// Results
// first_name, Sammy
// nick_name, Honey Badger
Code language: JavaScript (javascript)
-
.get(name)
: returns the first value of a key in the FormData object.- example
//JavaScript
formData.get('nick_name')
//returns 'Honey Badger'
Code language: JavaScript (javascript)
-
.getAll(name)
: returns an array of all the values associated with a key.- example
//JavaScript
formData.append('last_name', 'Messi');
formData.append('last_name', 'Ronaldo');
formData.getAll('last_name')
// RESULT
// ['Messi', 'Ronaldo']
Code language: JavaScript (javascript)
-
.has(name)
: returns a boolean value if the FormData object has a certain key.- example
//JavaScript
formData.has('other_name') // false
Code language: JavaScript (javascript)
-
.keys()
: returns an iterator that loops through all the keys contained in the FormData object.- example
//JavaScript
for (const key of formData.keys()) {
console.log(key);
}
// first_name
// last_name
// nick_name
Code language: JavaScript (javascript)
-
.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
//JavaScript
formData.set('last_name', 'Fati');
formData.get('last_name'); // "Fati"
Code language: JavaScript (javascript)
-
.values
: returns an iterator that loops through all the values contained in the FormData object.- example
//JavaScript
for (const value of formData.values()) {
console.log(value);
}
// Sammy
// Honey Badger
// Fati
// Messi
// Ronaldo
Code language: JavaScript (javascript)
Now we know the methods FormData provides us, let’s go through some real-world samples.
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.
<!--HTML --!>
<form id="form">
<input type="text" name="first_name" value="Sammy">
<input type="text" name="nick_name" value="Honey Badger">
<input type="password" name="password" value="password123">
</form>
<pre id="output"></pre>
Code language: PHP (php)
//JavaScript
const form = document.getElementById("form");
const formData = new FormData(form)
const output = document.getElementById("output")
for (const [key, value] of formData) {
output.textContent = output.textContent + `${key}: ${value}\\n`;
}
Code language: JavaScript (javascript)
Let’s work on a more realistic example.
//JavaScript
const submit = async () => {
try {
const formData = new FormData
formData.append('myFileData', document[0])
let response = await fetch('/upload', {
method: 'POST',
body: formData,
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
});
const result = await response.json();
showMessage(result.message, response.status == 200 ? 'success' : 'error');
} catch (error) {
showMessage(error.message, 'error');
}
Code language: JavaScript (javascript)
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.
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