What is Form Method in HTML: Explanation and Examples
method attribute of a <form> element specifies how form data is sent to the server. It usually has two values: GET (data sent in the URL) or POST (data sent in the request body). This controls how the browser submits the form information.How It Works
Think of a form on a website like a letter you want to send. The method attribute decides how you send that letter to the post office (the server). If you use GET, it's like writing your message on the outside of the envelope, so anyone can see it. This means the data is added to the URL, making it easy to bookmark or share but less secure for sensitive info.
If you use POST, it's like putting your message inside the envelope, hidden from view. The data is sent in the request body, which is better for private or large amounts of data. The server then reads this data to process your request.
Example
This example shows a simple form using the POST method to send a username and password securely.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Form Method Example</title> </head> <body> <form action="/submit-login" method="post"> <label for="username">Username:</label> <input type="text" id="username" name="username" required> <br><br> <label for="password">Password:</label> <input type="password" id="password" name="password" required> <br><br> <button type="submit">Login</button> </form> </body> </html>
When to Use
Use the GET method when you want to retrieve or search for data without changing anything on the server. For example, a search box on a website often uses GET because the search terms can be shown in the URL.
Use the POST method when you need to send sensitive information, like passwords or personal details, or when you want to create or update data on the server. This keeps the data hidden from the URL and can handle larger amounts of information.
Key Points
- The
methodattribute controls how form data is sent to the server. GETappends data to the URL and is good for simple, non-sensitive requests.POSTsends data inside the request body, suitable for sensitive or large data.- Choosing the right method improves security and user experience.