Html with post example

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.

Читайте также:  Network automation with python

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.

Источник

Отправка данных формы

Сама форма обычно предназначена для получения от пользователя информации для дальнейшей пересылки её на сервер, где данные формы принимает программа-обработчик. Такая программа может быть написана на любом серверном языке программирования вроде PHP, Perl и др. Адрес программы указывается в атрибуте action тега , как показано в примере 1.

Пример 1. Отправка данных формы

В этом примере данные формы, обозначенные атрибутом name ( login и password ), будут переданы в файл по адресу /example/handler.php. Если атрибут action не указывать, то передача происходит на адрес текущей страницы.

Передача на сервер происходит двумя разными методами: GET и POST, для задания метода в теге используется атрибут method , а его значениями выступают ключевые слова get и post . Если атрибут method не задан, то по умолчанию данные отправляются на сервер методом GET. В табл. 1 показаны различия между этими методами.

Табл. 1. Различия между методами GET и POST

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.

Источник

POST

The HTTP POST method sends data to the server. The type of the body of the request is indicated by the Content-Type header.

The difference between PUT and POST is that PUT is idempotent: calling it once or several times successively has the same effect (that is no side effect), where successive identical POST may have additional effects, like passing an order several times.

A POST request is typically sent via an HTML form and results in a change on the server. In this case, the content type is selected by putting the adequate string in the enctype attribute of the element or the formenctype attribute of the or elements:

  • application/x-www-form-urlencoded : the keys and values are encoded in key-value tuples separated by ‘&’ , with a ‘=’ between the key and the value. Non-alphanumeric characters in both keys and values are URL encoded: this is the reason why this type is not suitable to use with binary data (use multipart/form-data instead)
  • multipart/form-data : each value is sent as a block of data («body part»), with a user agent-defined delimiter («boundary») separating each part. The keys are given in the Content-Disposition header of each part.
  • text/plain

When the POST request is sent via a method other than an HTML form — like via an XMLHttpRequest — the body can take any type. As described in the HTTP 1.1 specification, POST is designed to allow a uniform method to cover the following functions:

  • Annotation of existing resources
  • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
  • Adding a new user through a signup modal;
  • Providing a block of data, such as the result of submitting a form, to a data-handling process;
  • Extending a database through an append operation.

Syntax

Example

A simple form using the default application/x-www-form-urlencoded content type:

http

POST /test HTTP/1.1 Host: foo.example Content-Type: application/x-www-form-urlencoded Content-Length: 27 field1=value1&field2=value2 

A form using the multipart/form-data content type:

POST /test HTTP/1.1 Host: foo.example Content-Type: multipart/form-data;boundary="boundary" --boundary Content-Disposition: form-data; name="field1" value1 --boundary Content-Disposition: form-data; name="field2"; filename="example.txt" value2 --boundary-- 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 10, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Оцените статью