Recipe 7.2
Submitting a Form with Fetch and the FormData API
Imagine a form to add a new user. The API for this form requires an API token that is stored in memory. This example shows how to use the FormData
API to add extra data before submitting the form.
Enter a username (or keep the default one), and click Submit. The API token is added to the request.
The form endpoint will echo back the data it received, so you can see the API token that was added.
Demo
Add User
Received form data:
Code
JavaScript
const form = document.querySelector('#user-form');
// In a real world application, the API token would be stored somewhere and
// not hard coded like this.
const apiToken = 'aBcD1234EfGh5678IjKlM';
form.addEventListener('submit', event => {
event.preventDefault();
const data = new FormData(event.target);
data.set('apiToken', apiToken);
fetch('/api/form', {
method: 'POST',
body: data
})
.then(response => response.json())
.then(body => renderResults(body));
});
function renderResults(result) {
const resultContainer = document.querySelector('#result');
const list = resultContainer.querySelector('ul');
for (const [key, value] of Object.entries(result)) {
const item = document.createElement('li');
item.innerHTML = `<strong>${key}</strong>: ${value}`;
list.appendChild(item);
}
resultContainer.classList.remove('d-none');
}
HTML
<h3>Add User</h3>
<form id="user-form" class="mb-3">
<div class="mb-3">
<label class="form-label" for="username">Username</label>
<input required class="form-control" name="username" id="username" value="john.doe">
</div>
<button class="btn btn-primary">Submit</button>
</form>
<div id="result" class="alert alert-primary d-none" role="alert">
<h4>Received form data:</h4>
<ul></ul>
</div>