HTML Forms

HTML Forms are used when you want to collect some data from your users.

For example when you want to register some users, you need a form to collect thier information like name, email address, phone number etc. Then the form data is sent through scripts like PHP to database.

HTML <form> Element

The HTML <form> tag is used to create an HTML Form.

Syntax of HTML Form is:


<form>
<!--Form elements like input fields come here-->
</form>

Form Attributes

There some attributes used in forms other than normal attributes. These are:

S.no Attribute Name Description
1. action It defines the action to be performed when the form is submitted. Usually, the form data is sent to a page on the server when the user clicks on the submit button.
If it is omitted then the action is set to the same page.
2. target This attribute is used to specify whether to open the submitted form result in a new tab, any frame or in the same window.
The default value is _self which means the form will be submitted in the same window.
For opening the form result in the new tab use _blank.
3. Method It is used to specify the HTTP method to be used when submitting the form data.
There are two methods GET and POST.

When we should use GET?

By default HTTP method GET is used for submitting the form data.

It is not used for sensitive data as it shows the form data in the page's address field:

/action.php?firstname=Ajay&lastname=Singh

Pros:
  • Appends the data in url as the pairs of name and value.
  • Useful in bookmarking results.
  • Useful for non-secure data used in jquery.
Cons:
  • Url length is limited upto 2048 characters.
  • Not for sensitive data like passwords.

When we should use POST?

It is used for dealing with sensitive data in forms as it does not show that data in the page's address field.

Pros:
  • No size limitations.
  • Can be used with sensitive data in forms like passwords.
Cons:
  • Form result cannot be bookmarked.