Sub topic 13
Reading and Sending Form Data with JavaScript
This chapter assumes you know the form element, how name and value pairs are built, and the built-in validation attributes. You also need basic JavaScript: event listeners, fetch, and promises. By the end you will be able to intercept a submission, read the data with FormData, and send it to a server without a page reload.
Why use JavaScript for submission
A plain form submission navigates the browser to the response page. That is simple and reliable. JavaScript becomes useful when you want to:
- stay on the page and show a message in place
- send JSON instead of the form encoding
- add extra data, or change data, before sending
- disable the button while a request runs
Keep the action and method attributes on the form even when you script it. If the script fails to load, the form still works as a normal submission.
The submit event
The submit event fires on the form element, not on the button. It fires when the user clicks a submit button or presses Enter in a text field. It also fires when you call form.requestSubmit().
The event fires only after built-in validation passes. If a control is invalid, the browser shows its message and the event never fires. So you do not need to re-check required or pattern inside the handler.
<form id="subscribe" action="/subscribe" method="post">
<label for="email">Email address</label>
<input id="email" name="email" type="email" autocomplete="email" required>
<button type="submit">Subscribe</button>
</form>
<p id="status" role="status"></p>Calling event.preventDefault() stops the browser's own navigation. Without it, your code runs and then the page submits anyway.
const form = document.querySelector('form');
form.addEventListener('submit', (event) => {
event.preventDefault();
const data = new FormData(form);
console.log(Object.fromEntries(data));
});Listen for submit on the form. Do not listen for click on the button. A click listener misses Enter-key submissions and runs before validation.
The diagram below shows the order of events.
What FormData collects
new FormData(form) builds a list of name and value pairs from the form's controls. It follows the same rules as a native submission, which this tutorial covered in the chapter on names and values. A control is included only if it is a successful control:
- It has a
name. - It is not disabled.
- Checkboxes and radio buttons are included only if checked.
- A
selectcontributes the value of each selected option. - Buttons are not included, unless you pass the submitter (see below).
The most common surprise is that an unchecked checkbox is simply absent. Code that expects data.get('newsletter') to be "no" gets null instead.
Reading values
FormData is not a plain object. It is a collection of entries that may repeat a name. Use its methods:
| Method | Returns |
|---|---|
| `get(name)` | The first value for the name, or `null` |
| `getAll(name)` | An array of every value for the name |
| `has(name)` | `true` if the name is present |
| `set(name, value)` | Replaces all entries with that name by one |
| `append(name, value)` | Adds an entry and keeps existing ones |
| `delete(name)` | Removes all entries with that name |
Values are strings, except for file inputs, which give File objects. A type="number" input still produces a string such as "3". Convert it yourself with Number() when you need arithmetic.
Repeated names
Several checkboxes can share a name, and a select multiple can send several values. Object.fromEntries(data) keeps only the last value for a repeated name, so it silently loses data. Use getAll for those fields:
const form = document.querySelector('form');
form.addEventListener('submit', (event) => {
event.preventDefault();
const data = new FormData(form);
const toppings = data.getAll('topping');
const single = Object.fromEntries(data);
console.log(toppings); // for example ["cheese", "olives"]
console.log(single.topping); // only the last one: "olives"
});If your form has repeated names, build the object by hand:
function formToObject(data) {
const result = {};
for (const key of new Set(data.keys())) {
const values = data.getAll(key);
result[key] = values.length > 1 ? values : values[0];
}
return result;
}This returns an array only for names that actually repeat. A field that sometimes has one value and sometimes several then changes type, so a consistent rule can be safer. For example, decide ahead of time which field names are lists.
Sending the data with fetch
You can pass a FormData object directly as the body of fetch. The browser chooses the encoding for you.
const form = document.querySelector('#subscribe');
const status = document.querySelector('#status');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const button = form.querySelector('button[type="submit"]');
button.disabled = true;
status.textContent = 'Sending…';
try {
const response = await fetch(form.action, {
method: form.method,
body: new FormData(form),
});
if (!response.ok) {
throw new Error(`Server returned ${response.status}`);
}
status.textContent = 'Thanks, you are subscribed.';
form.reset();
} catch (error) {
status.textContent = 'Could not send the form. Please try again.';
} finally {
button.disabled = false;
}
});Points to notice:
form.actionreturns an absolute URL, andform.methodreturns a lowercase string.fetchaccepts both.fetchrejects its promise only for network failures. A404or500response resolves normally, so you must checkresponse.ok.- The button is disabled during the request to prevent double submissions. Disable it after you build
FormData, or the data is still fine because the button is never a field. Disabling a named control before buildingFormDatawould drop that control. form.reset()restores the default values defined in the HTML.
Three encodings
The encoding of the request body depends on what you pass to fetch.
| Body you pass | Content-Type sent | Notes |
|---|---|---|
| `FormData` | `multipart/form-data; boundary=...` | Works with files. Set by the browser. |
| `URLSearchParams` | `application/x-www-form-urlencoded` | Matches the form's default encoding. |
| JSON string | Whatever header you set | You must set `Content-Type: application/json`. |
For a FormData body, never set the Content-Type header yourself. The browser must add the boundary value, and a manual header removes it, so the server cannot parse the body.
To send URL-encoded data, convert the entries:
const body = new URLSearchParams(new FormData(form));
fetch('/subscribe', { method: 'POST', body });This fails if the form contains a file input. URLSearchParams expects strings, so each file becomes the text of the object, not its contents. Use FormData for forms with files.
To send JSON, build the object and stringify it:
const payload = formToObject(new FormData(form));
fetch('/api/subscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});Your server must expect JSON for this route. A server written for form posts will not parse it.
GET forms and fetch
With method: 'GET', a body is not allowed. Put the data in the query string instead:
const query = new URLSearchParams(new FormData(form)).toString();
const response = await fetch(`${form.action}?${query}`);Including the submit button
A native submission includes the name and value of the button that was clicked, if it has a name. new FormData(form) does not include it. Pass the button as a second argument. The SubmitEvent exposes it as event.submitter.
form.addEventListener('submit', (event) => {
event.preventDefault();
const data = new FormData(form, event.submitter);
console.log(data.get('action')); // "save" or "publish"
});This works with markup such as <button name="action" value="save"> and <button name="action" value="publish">. The second argument to the FormData constructor is supported in current browsers, but check older ones if you must support them.
Gotchas
- Disabled controls are skipped. If you disable inputs while sending, build
FormDatafirst. FormDatais a snapshot. Changing an input afterwards does not change an existing object.- Inputs outside the form. A control with
form="subscribe"belongs to that form even when it sits elsewhere in the page, andFormDataincludes it. - Console output.
console.log(formData)often shows an empty-looking object. Log[...formData]orObject.fromEntries(formData)to see the entries. - Files. An empty file input still sends an entry, with an empty filename and size 0. Check
file.sizebefore treating it as an upload. - Custom components. A custom element's value appears in
FormDataonly if it is form-associated or you add it withappend.
Exercises
Exercise
A form has three checkboxes named topping, and a user checks two. You call Object.fromEntries(new FormData(form)). How many toppings appear in the result, and what should you use instead to read all of them?
Show answer
Only one appears, the last checked value, because Object.fromEntries keeps the last entry for a repeated name. Use new FormData(form).getAll('topping'), which returns an array of both values.
Exercise
Your fetch call sends a FormData body and you add the header Content-Type: multipart/form-data. The server cannot parse the upload. Why, and what is the fix?
Show answer
A multipart body needs a boundary parameter in the header, and the browser generates it only when it sets the header itself. Remove your Content-Type header and let the browser set it.
Exercise
A user submits a form by pressing Enter in a text field. Why does a click listener on the submit button miss this case, and which event should you use?
Show answer
Pressing Enter in some fields starts a submission without a click on the button in all cases, and a click listener also runs before validation. Listen for the submit event on the form. It fires for every submission path, and only after built-in validation passes.