HTML Form Action: POST and GET

The method attribute in the <form> element specifies how the data is sent to the server.

HTTP methods declare what action is to be performed on the data that is submitted to the server. HTTP Protocol provides several methods, and the HTML Form element is able to use two methods to send user data:

  • GET method - used to request data from a specified resource
  • POST method - used to send data to a server to update a resource

The GET Method

The HTML GET method is used to get a resource from the server. For example,

<form method="get" action="www.programiz.com/search">
    <input type="search" name="location" placeholder="Search.." />
    <input type="submit" value="Go" />
</form>

When we submit the above form by entering California in the input field, the request sent to the server will be www.programiz.com/search/?location=California.

The HTTP GET method adds a query string at the end of the URL to send data to the server. The query string is in the form of key-value pair followed by ? symbol.

From the URL, the server can parse the user-submitted value where:

  • key - location
  • value - California

Note: If there is more than one query, the query string will be separated by a & symbol.


The POST method

The HTTP POST method is used to send data to the server for further processing. For example,

<form method="post" action="www.programiz.com/user">
    <label for="firstname">First name:</label>
    <input type="text" name="firstname" /><br />
    <label for="lastname">Last name:</label>
    <input type="text" name="lastname" /><br />
    <input type="submit" />
</form>

When we submit the form, it will add the user input data to the body of the request sent to the server. The request would look like

POST /user HTTP/2.0
Host: www.programiz.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 33

firstname=Robin&lastname=Williams

The data sent is not easily visible to the user. However, we can check the sent data using special tools like the browsers' dev tools.


GET vs POST

GET POST
Data sent with the GET method is visible in the URL. Data sent with the POST method is not visible.
GET requests can be bookmarked. POST requests can't be bookmarked.
GET requests can be cached. POST requests can't be cached.
GET requests have a character limit of 2048 characters. POST requests do not have a limit.
Only ASCII characters are allowed in GET requests. All data is allowed in POST request