JavaScript and forms

Pending, success, and error states

Design explicit submission states so a visitor knows whether the form is working, succeeded, or needs attention.

8 minute lesson

~~~

A JavaScript-enhanced form has at least four states: idle, pending, successful, and failed.

Make those states visible in the interface:

<button type="submit">Send message</button>
<p id="form-status" aria-live="polite"></p>

When submission starts, change the button label to “Sending…” and disable that submitter. Put a short message in the live region so the state is not communicated only through a spinner.

Wait for the server response before showing success. Receiving a network response does not always mean the operation succeeded, so inspect the status and expected response body.

Validation failure is different from network failure:

  • A validation response should identify fields and preserve their values.
  • A network failure should explain that the request could not be completed and allow a retry.
  • A server failure should avoid blaming the person’s input.

Do not clear the form when the request starts. If it fails, the person would lose their work. Reset only after confirmed success and only when an empty form makes sense.

Use a finally block to restore controls. Otherwise one thrown error can leave the button disabled forever.

Disabling a button reduces accidental double-clicks, but it does not make the endpoint duplicate-safe. Requests can be retried by the browser, network, or user.

Throttle the connection in DevTools and watch every transition. Then force an error and confirm the form returns to a usable state.

Lesson completed