Sub topic 13
Reading and sending form data with JavaScript
This chapter assumes you can build a form with named controls, know how name and value pairs become submitted data, and understand built-in validation attributes. You also need basic JavaScript: event listeners, objects, and fetch.
Why handle submission in JavaScript
A normal submission navigates the browser to the form's action URL. Handling the submit event lets you stay on the page. You can send the data in the background, show a message, or update part of the page.
The submit event fires only after built-in validation passes. If a control is invalid, the browser shows its message and the event never fires. You don't need to re-check required or pattern in your handler.
Reading data with FormData
FormData is an object that collects the successful controls of a form. A successful control has a name, is not disabled, and, for checkboxes and radio buttons, is checked.
const form = document.querySelector('form');
form.addEventListener('submit', (event) => {
event.preventDefault();
const data = new FormData(form);
console.log(Object.fromEntries(data));
});event.preventDefault() stops the browser from navigating. Passing the form to new FormData(form) reads the current values.
You can also read single values with data.get('email'), or all values for one name with data.getAll('topic').
The repeated-name gotcha
Object.fromEntries keeps only the last value when a name repeats. A group of checkboxes that share the name topic would lose all but one value. Use getAll for those names:
const data = new FormData(form);
const topics = data.getAll('topic'); // every checked boxUnchecked checkboxes are absent from FormData, so data.get('newsletter') returns null when the box is unchecked.
Sending the data
Pass the FormData directly to fetch to send a multipart/form-data request. This also works for file inputs.
form.addEventListener('submit', async (event) => {
event.preventDefault();
const response = await fetch(form.action, {
method: form.method,
body: new FormData(form),
});
if (!response.ok) {
console.error('Server returned', response.status);
}
});Don't set the Content-Type header yourself. The browser adds it along with the boundary string that separates the parts. Setting it manually breaks the request.
To send a URL-encoded body like a default form does, wrap the data:
const body = new URLSearchParams(new FormData(form));
await fetch(form.action, { method: 'POST', body });To send JSON, convert the data and set the header yourself:
await fetch(form.action, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.fromEntries(new FormData(form))),
});The server must expect JSON for this to work.
Common errors
| Symptom | Likely cause |
|---|---|
| A field is missing from the data | The control has no `name`, or it is disabled |
| A checkbox value is missing | It was unchecked, so it was not submitted |
| Only one checkbox value arrives | `Object.fromEntries` dropped repeats; use `getAll` |
| Page reloads anyway | `preventDefault()` was not called, or the handler threw an error before reaching it |
| Upload fails on the server | A manual `Content-Type` header removed the multipart boundary |
Exercise
A form has three checkboxes named topic, and the user checks two of them. Why does Object.fromEntries(new FormData(form)) return only one topic, and how do you get both?
Show answer
Object.fromEntries builds an object, and an object can hold one value per key, so the later topic entry overwrites the earlier one. Call new FormData(form).getAll('topic') to get an array with both checked values.
Exercise
Your fetch upload sends body: new FormData(form) with the header 'Content-Type': 'multipart/form-data', and the server cannot parse it. What is wrong?
Show answer
The manual header lacks the boundary string. Remove the header and let the browser set it, including the boundary, when the body is a FormData object.