- Отправка данных формы
- GET
- POST
- HTML Forms
- Example
- The Element
- The Element
- Text Fields
- Example
- The Element
- Radio Buttons
- Example
- Checkboxes
- Example
- The Submit Button
- Example
- Example
- HTML Forms
- The HTML element
- Text input
- Example of the text input:
- Radio Button Input
- Example of the radio button input:
- Submit input
- Example of the submit input:
- The Action Attribute
- The Target Attribute
- The Method Attribute
- Example of the GET method:
- Example of the POST method:
- When to use the GET Method
- When to use the POST Method
- Other Attributes
Отправка данных формы
Сама форма обычно предназначена для получения от пользователя информации для дальнейшей пересылки её на сервер, где данные формы принимает программа-обработчик. Такая программа может быть написана на любом серверном языке программирования вроде PHP, Perl и др. Адрес программы указывается в атрибуте action тега , как показано в примере 1.
Пример 1. Отправка данных формы
В этом примере данные формы, обозначенные атрибутом name ( login и password ), будут переданы в файл по адресу /example/handler.php. Если атрибут action не указывать, то передача происходит на адрес текущей страницы.
Передача на сервер происходит двумя разными методами: GET и POST, для задания метода в теге используется атрибут method , а его значениями выступают ключевые слова get и post . Если атрибут method не задан, то по умолчанию данные отправляются на сервер методом GET. В табл. 1 показаны различия между этими методами.
GET | POST | |
---|---|---|
Ограничение на объём | 4 Кб | Ограничения задаются сервером. |
Передаваемые данные | Видны сразу всем. | Видны только при просмотре через расширения браузера или другими методами. |
Кэширование | Страницы с разными запросами считаются различными, их можно кэшировать как отдельные документы. | Страница всегда одна. |
Закладки | Страницу с запросом можно добавить в закладки браузера и обратиться к ней позже. | Страницы с разными запросами имеют один адрес, запрос повторить нельзя. |
Какой метод используется легко определить по адресной строке браузера. Если в ней появился вопросительный знак и адрес стал похож на этот, то это точно GET.
Уникальное сочетание параметров в адресной строке однозначно идентифицирует страницу, так что страницы с адресами ?q=node/add и ?q=node считаются разными. Эту особенность используют системы управления контентом (CMS, Content management system) для создания множества страниц сайта. В реальности же используется один файл, который получает запрос GET и согласно ему формирует содержимое документа.
Ниже перечислены типовые области применения этих методов на сайтах.
GET
Передача небольших текстовых данных на сервер; поиск по сайту.
Поисковые системы, формы поиска по сайту всегда отправляются методом GET, это позволяет делиться результатами поиска с друзьями, слать ссылку по почте или выкладывать её на форуме.
POST
Пересылка файлов (фотографий, архивов, программ и др.); отправка комментариев; добавление и редактирование сообщений на форуме, блоге.
Работа с формой по умолчанию происходит в текущей вкладке браузера, при этом допустимо при отправке формы изменить этот параметр и открывать обработчик формы в новой вкладке или во фрейме. Такое поведение задаётся через «имя контекста», которое выступает значением атрибута target тега . Популярные значения это _blank для открытия формы в новом окне или вкладке, и имя фрейма, которое задаётся атрибутом name тега (пример 2).
Пример 2. Открытие формы во фрейме
В данном примере при нажатии на кнопку «Отправить» результат отправки формы открывается во фрейме с именем area .
Элементы формы традиционно располагаются внутри тега , тем самым определяя те данные, которые будут передаваться на сервер. В то же время в HTML5 есть возможность отделить форму от её элементов. Это сделано для удобства и универсальности, так, сложный макет может содержать несколько форм, которые не должны пересекаться меж собой или к примеру, некоторые элементы выводятся с помощью скриптов в одном месте страницы, а сама форма находится в другом. Связь между формой и её элементами происходит в таком случае через идентификатор формы, а к элементам следует добавить атрибут form со значением, равным этому идентификатору (пример 3).
Пример 3. Связывание формы с полями
В этом примере тег однозначно отождествляется через идентификатор auth , а к полям, которые следует отправить с помощью формы, добавляется form=»auth» . При этом поведение элементов не меняется, при нажатии на кнопку логин и пароль пересылаются на обработчик handler.php.
Хотя параметры передачи формы традиционно указываются в теге , их можно перенести и в кнопки отправки формы ( и ). Для этого применяется набор атрибутов formaction , formmethod , formenctype и formtarget , которые являются аналогами соответствующих атрибутов без приставки form. В примере 4 показано использование этих атрибутов.
Все новые атрибуты форм не поддерживаются некоторыми браузерами, в частности, Internet Explorer и Safari.
HTML Forms
An HTML form is used to collect user input. The user input is most often sent to a server for processing.
Example
The Element
The HTML element is used to create an HTML form for user input:
The element is a container for different types of input elements, such as: text fields, checkboxes, radio buttons, submit buttons, etc.
All the different form elements are covered in this chapter: HTML Form Elements.
The Element
The HTML element is the most used form element.
An element can be displayed in many ways, depending on the type attribute.
Type | Description |
---|---|
Displays a single-line text input field | |
Displays a radio button (for selecting one of many choices) | |
Displays a checkbox (for selecting zero or more of many choices) | |
Displays a submit button (for submitting the form) | |
Displays a clickable button |
All the different input types are covered in this chapter: HTML Input Types.
Text Fields
The defines a single-line input field for text input.
Example
A form with input fields for text:
This is how the HTML code above will be displayed in a browser:
Note: The form itself is not visible. Also note that the default width of an input field is 20 characters.
The Element
Notice the use of the element in the example above.
The tag defines a label for many form elements.
The element is useful for screen-reader users, because the screen-reader will read out loud the label when the user focuses on the input element.
The element also helps users who have difficulty clicking on very small regions (such as radio buttons or checkboxes) — because when the user clicks the text within the element, it toggles the radio button/checkbox.
The for attribute of the tag should be equal to the id attribute of the element to bind them together.
Radio Buttons
The defines a radio button.
Radio buttons let a user select ONE of a limited number of choices.
Example
A form with radio buttons:
Choose your favorite Web language:
This is how the HTML code above will be displayed in a browser:
Choose your favorite Web language:
Checkboxes
The defines a checkbox.
Checkboxes let a user select ZERO or MORE options of a limited number of choices.
Example
This is how the HTML code above will be displayed in a browser:
I have a bike
I have a car
I have a boat
The Submit Button
The defines a button for submitting the form data to a form-handler.
The form-handler is typically a file on the server with a script for processing input data.
The form-handler is specified in the form’s action attribute.
Example
A form with a submit button:
This is how the HTML code above will be displayed in a browser:
The Name Attribute for
Notice that each input field must have a name attribute to be submitted.
If the name attribute is omitted, the value of the input field will not be sent at all.
Example
This example will not submit the value of the «First name» input field:
HTML Forms
An HTML form is composed of form elements, which are different kinds of input elements, such as checkboxes, text fields, submit buttons, radio buttons, and so on.
The HTML element
Let’s speak about some of input types.
Text input
Example of the text input:
html> html> head> title>Title of the document title> head> body> h2>Text Input Example h2> form> Name:br> input type="text" name="name"> br> Surname:br> input type="text" name="surname"> form> body> html>
Radio Button Input
Example of the radio button input:
html> html> head> title>Title of the document title> head> body> h2>Radio Button Example h2> form> input type="radio" name="game"value="football" checked> Football input type="radio" name="game" value="basketball"> Basketball form> body> html>
Submit input
The submits the form data to a form-handler.
The form-handler is a server page with a script to process input data, which is defined in the action attribute of the form.
Example of the submit input:
html> html> head> title>Title of the document title> head> body> h2>HTML Form Example h2> form action="/form/submit" method="POST"> Name:br> input type="text" name="firstname" value="Tom"> br> Surname:br> input type="text" name="lastname" value="Brown"> br> Age:br> input type="text" name="Age" value="21"> br>br> input type="submit" value="Submit"> form> p>Click the "Submit" button, to sent the form-data to the action page. p> body> html>
The Action Attribute
The action attribute specifies the action that should be performed when the form is submitted.
When the user the form data is sent to a web page on the server when the user clicks on the submit button.
The Target Attribute
The target attribute defines whether the form result is open in a new browser tab, frame, or in the current window.
The default value of this attribute is _self . Using this value will open the form result in the current window.
The _blank value will open the form result open in a new browser tab.
form action="/form/submit" target="_blank">
The Method Attribute
The method attribute defines the HTTP method (GET or POST) that will be used when submitting the form data.
Example of the GET method:
html> html> head> title>Title of the document title> head> body> h2>The method Attribute With the GET Method h2> form action="/form/submit" target="_blank" method="GET"> Neame:br> input type="text" name="name" value="Tom"> br> Surname:br> input type="text" name="Surname" value="Brown"> br> Age:br> input type="number" name="Aage" value="21"> br>br> input type="submit" value="Submit"> form> p> Here we used the "_blank" value, which will open the form result in a new browser tab. p> body> html>
Example of the POST method:
html> html> head> title>Title of the document title> head> body> h2>The method Attribute With the Post Method h2> form action="/form/submit" target="_blank" method="POST"> Name:br> input type="text" name="name" value="Tom"> br> Surname:br> input type="text" name="surname" value="Brown"> br> Age:br> input type="number" name="age" value="21"> br>br> input type="submit" value="Submit"> form> body> html>
When to use the GET Method
GET is the default method when submitting form data, and when using this method the form data is visible in the page address field.
When to use the POST Method
If the form data includes sensitive or personal information, always use the POST method, as it doesn’t display the submitted form data in the page address field.
As there are no size limitations while using the POST method, it can be used to send large amounts of data.
Form submissions with the POST method can’t be bookmarked.
Other Attributes
Below you can find other attributes:
Attribute | Description |
---|---|
accept-charset | This attribute defines the charset that is used in the submitted form (default: the page charset). |
autocomplete | This attribute defines whether the browser should autocomplete the form or not (default: on). |
enctype | This attribute defines the encoding of the submitted data (default:url-encoded). |
name | This attribute defines a name that is used to identify the form. |
novalidate | This attribute defines that the browser must not validate the form. |