Submitting a form is a page navigation. The browser gathers the values, sends a request to the action URL, and replaces the page with whatever comes back.
That default is fine for a traditional site. It is also exactly what you want to change when you want to send the data with fetch and keep the page in place.
Understanding the default first makes the JavaScript version much easier to reason about, because you always know what you are replacing.
The previous lesson in this module covered "How Do Selects, Checkboxes and Radios Differ?", and the next lesson in this module is about "How Does Built-In HTML Form Validation Work?".
What do the three button types do?
The type attribute on a button decides what it does, and the default is the one that catches people out.
<button type="submit">Save</button> <!-- sends the form (this is the default) -->
<button type="reset">Clear</button> <!-- restores the initial values -->
<button type="button">Open dialog</button> <!-- does nothing on its own -->Inside a form, a button with no type is a submit button.
That is the reason a button that was meant to open a dialog sometimes submits the form and reloads the page instead.
The fix is always the same. You give it the type="button".
There is a second submit control worth knowing, which is the <input type="submit"> form control. It cannot contain any child elements, so it cannot have an icon inside it. The <button> element can, and it is the more flexible of the two.
What happens when the form is submitted?
Three things happen, in this order. The browser runs the built-in validation, it fires a submit event, and, if nothing cancelled it, it navigates to the action URL.
const form = document.querySelector('form');
form.addEventListener('submit', (event) => {
event.preventDefault(); // stop the navigation
const data = Object.fromEntries(new FormData(form));
console.log(data);
// fetch(form.action, { method: form.method, body: new FormData(form) })
});The call to preventDefault() is what turns a traditional submission into a JavaScript one.
The FormData object is the useful part. It collects every named control, including the files, into the same structure that the server would have received, so you can send it with fetch without writing the serialisation yourself.
async function send(form) {
const response = await fetch(form.action, {
method: form.method || 'post',
body: new FormData(form)
});
const result = await response.json();
console.log(result);
}Does the form work without JavaScript?
It should, and that is a design decision rather than an accident of implementation.
A form that posts to a URL and renders the result as a new page works with no JavaScript at all. That matters for reliability, for old browsers, and for anybody whose script failed to load.
If you intercept the submit event, you are adding behaviour on top of a mechanism that already works.
<form action="/subscribe" method="post">
<label for="email">Email address</label>
<input type="email" id="email" name="email" required>
<button type="submit">Subscribe</button>
</form>The pattern to keep is progressive enhancement. You build the form so that it works, and then you improve it with JavaScript.
If the enhancement fails, the visitor still completes the task.
How do you check the data before sending?
The built-in validation of the browser runs first. If it fails, the submission is stopped and the offending field is marked.
When you handle the submit event yourself, you can add your own checks on top of that.
form.addEventListener('submit', (event) => {
if (!form.checkValidity()) {
event.preventDefault();
form.reportValidity(); // shows the browser's own messages
return;
}
// ...send it
});Two methods do the work. The checkValidity() returns true or false, and the reportValidity() shows the same messages that the browser would have shown.
Using them keeps your messages consistent with the ones the visitor has already seen.
What happens when the visitor presses Enter?
In a form with a single text field, pressing Enter submits it.
In a form with several fields, Enter in any of them usually submits the form as well, because the browser treats it as an implicit submission.
This is convenient, and it is also a hazard. A visitor who is tabbing through a long form can accidentally submit a half-finished page.
<!-- Enter in this field does not submit the form -->
<input type="text" name="search" form="search-form">
<!-- but this button submits it -->
<button type="submit" form="search-form">Search</button>The form attribute associates a control with a form by its id, so you can place a button or a field outside the form element and it still belongs to that form.
That gives you control over where the submit action lives.
How do I stop a double submission?
On a slow connection, a visitor clicks submit twice. The form is sent twice, and that often means two records instead of one.
The usual defence is to disable the button as soon as the submission starts.
form.addEventListener('submit', (event) => {
event.preventDefault();
const button = form.querySelector('button[type="submit"]');
button.disabled = true;
button.textContent = 'Sending…';
fetch(form.action, { method: 'post', body: new FormData(form) })
.finally(() => {
button.disabled = false;
button.textContent = 'Subscribe';
});
});Notice that the button is re-enabled in the finally block, so a failed request does not leave the form permanently stuck.
On the server, the real fix is an idempotency key or a uniqueness constraint. A disabled button improves the experience, but only the server can guarantee that a request is not processed twice.
What can you do with the submitted data?
The FormData object gives you everything in one structure, and it handles the awkward cases for you.
Multiple values under the same name become a list, the files appear as File objects, and nothing needs to be stringified by hand.
const data = new FormData(form);
console.log(data.get('email')); // one value
console.log(data.getAll('topics')); // every value for a repeated name
console.log(data.get('avatar')); // a File object
console.log(Object.fromEntries(data)); // a plain objectTwo details catch people out.
The get() method returns a null when the field is absent, while the getAll() method returns an empty array. Check for both instead of assuming.
And Object.fromEntries loses repeated names, because a plain object can only hold one value per key. Use it only when the form has no repeated field names.
Quick reference
- A button inside a form is a submit button unless you say otherwise.
- The
preventDefault()call on the submit event stops the navigation. - The
FormDataobject collects the named controls exactly as the server would receive them. - You build the form so that it works without JavaScript, and then you enhance it.
- The
checkValidity()andreportValidity()methods reuse the browser's own validation.
Try it yourself: you add a submit button to a form and you watch the page navigate on submit. Then you intercept the event, you log the collected data, and you send it with fetch instead. Finally, you disable the JavaScript half and you confirm that the form still submits and that the server receives the values.