Forms contain inputs

a <form> is an HTML element that contains input elements

MDN: form

Form Example

<form method='post'>
  Name: <input type='text' name='name' value='Alice'>
  Password: <input type='password' name='password'>
  <input type='submit'>

Forms are semantic

Form attributes

<form method='get' action='/login'>

Form Methods: GET vs. POST

Basically, GET is for reading and POST is for writing

but that distinction is often blurry


Form elements

<form method='GET' action='/search'>
  <label>Search by Author: <input type="search" name="author"></label>
  <input type='submit' value='Search'>

There are many more types of form elements (or "widgets") that let the user enter data in a wide variety of formats.

Intercepting forms with JavaScript

Form submission: how does it work?

client-server illustration

  1. The user enters some values into the form elements
  2. Either...
    • the user clicks "Submit"
    • or the user presses Enter in a text field
    • or JavaScript calls form.submit() on the form DOM element
  3. The client sends an HTTP request
    • including parameters like q=apple&submit=Search
    • (yes, the submit button's text label becomes the value)

Form submission in detail

Form reply: body

After the server receives and processes the request, it can return any HTTP response.

Usually that request is a full HTML page (for display to the user) or a JSON document (for use by your client-side app).

Form reply: redirect

Sometimes the response is a 302 redirect which helps keep your endpoints and address bar clean:

  1. form page, visible before the user starts entering values
  2. form submit handler, which redirects to...
  3. results page

...but many times it's an all-in-one handler which redraws the original page.

Form reply: error

Sometimes the response is an error.

It's important for you to design your app to be robust, meaning that if an error happens, it will fail gracefully.

Usually this means informing the user that the request could not be completed, and giving them the option to try again immediately, or asking them to try again later.

In the Fetch API, you can provide an catch callback which will receive network errors if and when they happen; you can also check if (!response.ok) { inside your main then callback.


References - docs - guide

 Previous Next