Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 39 ยท Building AJAX User Interfaces

Submitting Forms with AJAX

Submit HTML forms without a page reload: stop the default submit, read FormData, send JSON, show validation errors, disable the button and track uploads.

A normal HTML form sends the browser to a new page when you press the submit button. That is fine for a search box, but it is jarring for a comment form, a settings panel or a sign-up dialog: the page flashes, scroll position is lost, and anything the user typed is gone if the server rejects it. Submitting a form with AJAX keeps the page where it is. Your code sends the data in the background, waits for the answer and then updates only the part of the screen that needs to change.

The recipe has five steps: catch the submit event, collect the values, send them with fetch(), handle the three possible outcomes (success, validation errors, failure) and keep the interface honest while the request is running. This lesson builds that recipe piece by piece, then shows how file uploads and progress bars fit in.

About the examples. The sandbox cannot reach a real server, so the live demos use a small function that behaves like a server and returns real Response objects. Replace it with fetch("/api/...") and the rest of your code stays the same. Nothing on this page posts to the network.

Step one: catch the submit event

Listen for submit on the form, not for click on the button. The submit event also fires when the user presses Enter inside a text field, and it fires after the browser's built-in validation (required, type="email", minlength) has passed. Then call event.preventDefault() to stop the browser from navigating away:

JavaScript
const form = document.querySelector("#signup");

form.addEventListener("submit", async (event) => {
  event.preventDefault();   // no page load
  // collect, send, show result...
});

If you forget preventDefault(), the page reloads and your await never gets to finish. A good habit is to put it on the very first line of the handler.

Step two: collect the values with FormData

new FormData(form) reads every named, enabled control in the form and returns a FormData object: an ordered list of name/value pairs, exactly what the browser would have sent. Two details matter:

  • Only controls with a name attribute are included. An input without a name is invisible to FormData.
  • Unchecked checkboxes and radio buttons are left out entirely, and disabled controls are skipped.

FormData is iterable, so you can turn it into other shapes. The demo below shows the three you will use most often. Repeated names (like several checkboxes called topics) are the reason Object.fromEntries() is not always enough: it keeps only the last value for each name, so use getAll() for those.

JS Turning FormData into other shapes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Which shape should you send? It depends on what the server expects:

Body How to build it Content-Type
JSON JSON.stringify(object) application/json (set it yourself)
Multipart body: formData multipart/form-data; boundary=... (the browser sets it)
URL-encoded body: new URLSearchParams(formData) application/x-www-form-urlencoded (the browser sets it)

Send FormData whenever files are involved. For plain fields most JSON APIs prefer a JSON body.

flowchart LR
  A["User presses<br/>Submit"] --> B["submit event<br/>preventDefault()"]
  B --> C["new FormData(form)"]
  C --> D["fetch(url, options)"]
  D --> E{"Response"}
  E -->|"2xx"| F["Show success"]
  E -->|"422"| G["Show field errors"]
  E -->|"Network or 5xx"| H["Show retry message"]

The path of an AJAX form: one event, one request, three kinds of outcome.

Step three: handle every outcome

A server can answer a form in three very different ways, and each one needs its own interface:

  1. Success (200, 201): confirm it, clear or reset the form, maybe add the new item to a list.
  2. Validation failure (usually 422 Unprocessable Content, sometimes 400): the server understood the request but rejected the data. The body normally says which field is wrong. Keep the user's input and show each message next to its field.
  3. Failure (network error, 500, 503): nothing is wrong with the user's data, so show a general message and let them try again. Never wipe the form.

Notice that only the third case makes fetch() itself reject, and only for a network failure. A 422 is a normal response, so you branch on response.status or response.ok after the await. If you need a refresher, see handling errors in fetch.

Servers differ in how they describe field errors, but a common shape is an object keyed by field name:

JSON
{
  "message": "The data was invalid.",
  "errors": {
    "email": ["That address is already registered."],
    "password": ["Use at least 8 characters."]
  }
}

Your code maps each key to the input with the same name and writes the message into an element linked to it. Linking matters for accessibility: give each error element an id, point the input at it with aria-describedby, and set aria-invalid="true" on the input. Screen readers then announce the message when the field gets focus, and a status area with aria-live="polite" announces the general result.

Step four: keep the interface honest while waiting

While a request is running, the user needs to know something is happening and must not be able to fire it twice. Disable the submit button, change its label and restore both in a finally block so they come back whatever happens. Disable the button, not the whole form: disabled inputs are skipped by FormData, so disabling them before you read the values would lose the data.

The demo puts all four steps together. The fake server rejects an address that is already taken ([email protected]), short passwords and, one time in five, returns a 503. Try each case.

A sign-up form with validation feedback

Three details are worth copying. The form has novalidate so the demo's own messages show instead of the browser's bubbles (in a real project you can keep browser validation as a first line of defense and add required and type="email"). The handler maps errors by input.name, so adding a new field needs no new code. And the server is never trusted to be the only validator in the other direction either: client-side checks improve the experience, but the server must always validate again, because anyone can send requests without your form.

Sending the form as JSON, or as it is

Our demo converted the form with Object.fromEntries(new FormData(form)). Two small corrections are common in real code. Numbers arrive as strings, so convert fields like age with Number(). Checkboxes need care: a single checkbox is absent when unchecked, so read it from form.elements.newsletter.checked instead and add it to the object yourself.

If you want the browser to do the encoding and your server accepts it, you can skip the conversion:

JavaScript
await fetch("/api/profile", {
  method: "POST",
  body: new FormData(form),   // multipart/form-data, set by the browser
});

Do not set the Content-Type header by hand in this case; the browser needs to add the boundary value that separates the parts.

You can also reuse the form's own attributes, so the HTML stays the single source of truth for where and how to send:

JavaScript
const response = await fetch(form.action, {
  method: form.method,        // "post" works: fetch normalizes standard method names
  body: new FormData(form),
});

This also gives you progressive enhancement: with JavaScript the form is submitted in the background, and without it the browser still performs a normal submit to the same action.

Uploading files and showing progress

A file input contributes a File object to FormData, and fetch() uploads it as part of the multipart body. Make sure the form has <input type="file" name="avatar"> and that you do not convert the data into JSON, which cannot hold binary files.

fetch() can show download progress by reading the response stream, but it has no standard way to report upload progress. When a progress bar for an upload matters, the older XMLHttpRequest still does it well, through its upload.onprogress event. The sandbox cannot upload anywhere, so this block is read-only:

JavaScript
function uploadWithProgress(url, formData, onProgress) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open("POST", url);

    xhr.upload.addEventListener("progress", (event) => {
      if (event.lengthComputable) {
        onProgress(Math.round((event.loaded / event.total) * 100));
      }
    });

    xhr.addEventListener("load", () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve(JSON.parse(xhr.responseText));
      } else {
        reject(new Error("Upload failed: " + xhr.status));
      }
    });
    xhr.addEventListener("error", () => reject(new Error("Network error")));

    xhr.send(formData);
  });
}

// Usage
const bar = document.querySelector("progress");
await uploadWithProgress("/api/avatar", new FormData(form), (percent) => {
  bar.value = percent;
});

Before uploading, check the file on the client: file.size against a limit and file.type against the kinds you accept. This saves the user a slow upload that is going to be rejected, but remember that file.type comes from the browser and the server must verify uploads itself. The XMLHttpRequest lesson explains the rest of that API.

JS Checking a file before upload

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Using a click handler on the button. It misses Enter-key submits and bypasses built-in validation. Listen for submit.
  • Forgetting name attributes. FormData silently skips the field.
  • Disabling inputs before reading FormData. Read first, then disable.
  • Clearing the form on failure. Reset only after success.
  • Showing raw server messages. Map known error codes to friendly text and keep technical details for the console.
  • Letting double clicks through. A disabled button, or an isSubmitting flag, prevents duplicate records.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is submit on the form better than click on the button?

    The submit event fires however the form is submitted, including pressing Enter in a field, and only after the browser's own validation passed.
  2. 2. A form has <input id="city"> with no name attribute. What does new FormData(form) do with it?

    FormData collects only controls that have a name. The id is not used.
  3. 3. The server answers a sign-up request with status 422 and field errors. What happens to the promise from fetch()?

    fetch() rejects only when the request cannot be completed. A 422 is a normal response, so read the body and show the field messages.
  4. 4. You send body: formData containing a file. What should you do about the Content-Type header?

    A multipart body needs a boundary string in the header, and only the browser knows the one it generated.
  5. 5. Which API can report upload progress today?

    Fetch has no standard upload-progress event, while XHR exposes progress for the request body on xhr.upload.

Summary

  • Listen for the form's submit event and call event.preventDefault() to submit in the background.
  • new FormData(form) reads named, enabled controls; convert it with Object.fromEntries(), URLSearchParams or send it as the multipart body.
  • Handle three outcomes separately: success, validation errors (map them to fields with aria-invalid and aria-describedby) and network or server failure.
  • Disable the submit button while waiting and restore it in finally; keep user input when something fails.
  • Do not set Content-Type for FormData bodies; the browser adds the boundary.
  • Use XMLHttpRequest when you need upload progress; validate files on the client for convenience and on the server for safety.

Next: Live Search, Pagination and Infinite Scroll shows how to load results as the user types and as they scroll.