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//javascript2const 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');
- 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
1//JavaScript2const formData = new FormData()3formData.append('first_name', 'Sammy');4formData.append('nick_name', 'Honey Badger');56for(const entry of formData.entries()) {7 console.log(`${entry[0]}, ${entry[1]}`);8}910// Results1112// first_name, Sammy13// nick_name, Honey Badger
.get(name)
: returns the first value of a key in the FormData object.- example
1//JavaScript2formData.get('nick_name')3//returns 'Honey Badger'
.getAll(name)
: returns an array of all the values associated with a key.- example
1//JavaScript2formData.append('last_name', 'Messi');3formData.append('last_name', 'Ronaldo');45formData.getAll('last_name')67// RESULT89// ['Messi', 'Ronaldo']
.has(name)
: returns a boolean value if the FormData object has a certain key.- example
1//JavaScript2formData.has('other_name') // false
.keys()
: returns an iterator that loops through all the keys contained in the FormData object.- example
1//JavaScript2for (const key of formData.keys()) {3 console.log(key);4}56// first_name7// last_name8// 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//JavaScript2formData.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//JavaScript23for (const value of formData.values()) {4 console.log(value);5}67// Sammy8// Honey Badger9// Fati10// Messi11// 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>78<pre id="output"></pre>
1//JavaScript2const form = document.getElementById("form");3const formData = new FormData(form)4 const output = document.getElementById("output")56for (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//JavaScript2const submit = async () => {3 try {4 const formData = new FormData5 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();1415 showMessage(result.message, response.status == 200 ? 'success' : 'error');1617 } 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