(Progress persistence is disabled until Phase 9)
Form Actions and Submission
Learn how to finalize a form and understand how data is conceptually submitted.
Learning Objectives
- Learn how to create a submit button
- Understand the role of the form action attribute
- Conceptually understand how data is sent to a server
The Submit Button
A form is useless unless the user has a way to actually send the data. To do this, we need a submit button.
There are two ways to create a submit button in HTML:
<input type="submit"><button type="submit">Submit</button>
Both work, but the <button> tag is much more common in modern web development because it is easier to style with CSS and can contain icons or images inside it.
Code Example
<form action="/submit-data" method="POST">
<label for="email">Enter your email:</label>
<input type="email" id="email" name="user_email">
<button type="submit">Subscribe to Newsletter</button>
</form>
The Action Attribute
Let’s look at the <form> tag again.
<form action="/submit-data" method="POST">
When the user clicks the submit button, the browser packages up all the inputs inside the form and sends them to the URL specified in the action attribute.
If the action is /submit-data, the browser will leave the current page and navigate to /submit-data, handing the data over to the server.
The Method Attribute
The method attribute tells the browser how to send the data.
- GET: The data is appended directly to the URL (e.g.,
google.com/search?q=cats). This is great for search bars, but terrible for passwords! - POST: The data is sent secretly in the background body of the request. This is used for logging in, registering, or sending sensitive data.
If you use method="GET" for a login form, the user’s password will appear in plain text in their browser’s URL address bar! Always use POST for sensitive data.
Try It Yourself
Try adding a submit button to this form.
Key Takeaways
- Use
<button type="submit">to allow users to submit a form. - The
<form>tag must have anactionattribute telling the browser where to send the data. - Use
method="GET"for safe, shareable actions like searching. - Use
method="POST"for sensitive actions like logging in or submitting personal data.