Understanding HTML Forms
HTML forms enable web pages to collect user input and commmunicate with backend servers. When a user fills out a form and clicks submit, the data travels from the browser to the server, gets processed, and returns a response to the client.
Form are essential components for user interactions like login pages, registration forms, search inputs, and any interface requiring user input.
The Form Element
The <form> element acts as a container for various input controls:
<form action="submit.php" method="POST" name="contactForm">
<!-- form controls go here -->
</form>
Key attributes:
| Attribute | Purpose |
|---|---|
name |
Identifier for the form |
action |
Server endpoint URL to receive the data |
method |
HTTP method: GET or POST (defaults to GET) |
How Form Submission Works
When a form is submitted with method="POST", the data is sent in the HTTP request body and is not visible in the URL.
With method="GET", data appends to the URL as a query string:
http://example.com/search?q=keyword&category=books
GET vs POST comparison:
- GET: Data visible in URL, limited length, cached by browsers, faster for simple queries
- POST: Data hidden in request body, no size limit, more secure for sensitive information, required for file uploads
Complete Example
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User Login</title>
</head>
<body>
<form action="/api/login" method="POST">
<label for="email">Email:</label>
<input type="text" id="email" name="userEmail" /><br />
<label for="pass">Password:</label>
<input type="password" id="pass" name="userPassword" /><br />
<button type="submit">Sign In</button>
</form>
<!-- This input is outside the form and won't be submitted -->
<input type="text" name="externalField" />
</body>
</html>
Important Notes
Only form elements contained within the <form> tags are collected and submitted. Each input control must have a name attribute—the browser sends this name paired with the user's value as a key-value pair:
userEmail=user@example.com&userPassword=secret123
Multiple field pairs are concatenated with the & symbol.