Forms 101: Submitting a form

With the form:

  <input type='text' name='city' />

pressing enter in the input field will submit the form using a GET request.

Note that typically you’ll have a “submit” button in the form, but the form also submits in this way.

If you try typing “test” in the field and pressing enter, you’ll see the field is cleared and the URL changes from localhost:PORT to localhost:PORT/?city=test

This is the default behavior: data is sent using an HTTP GET request, and GET requests store the data in the URL using this format: ?key=value. This is called query string.

If you had more than one field, you’d see data separated using &, for example ?key1=value2&key2=value2

What you usually want to do, however, is using a POST request.

You do so by using the method attribute on the form element:

<form method='post'>
  <input type='text' name='city' />

Now the data is not sent in the URL as a query string any more, but it’s sent in the body of the HTTP POST request.

One interesting way to see this happening is by opening the devtools of your browser in the Network tab, and try submitting the form.

This is Chrome. See, we have a POST request:

and if you click it, it shows more details:

Switch to the Payload tab and you’ll see the form data:

The data in a POST request can be sent in different ways (JSON being a common one).

By default it’s sent URL-encoded, this is why you see the Content-Type HTTP header set to application/x-www-form-urlencoded.

By default the data is sent to the same route we’re visiting.

If we’re on http://localhost:PORT/, the form data is sent to the / route.

If we’re on http://localhost:PORT/test/, the form data is sent to the /test/ route.

We could override this behavior by setting the action attribute of the form element:

<form action="/contact" method="post">

Lessons this unit:

0: Introduction
1: Creating a form
2: ▶︎ Submitting a form
3: Receiving the form data
4: Form validation
5: More tags useful in forms