Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send data in the HTTP request body when using an HTML form?

The HTTP spec says that a POST request can contain an arbitrary body of data.

An HTML form element can POST to a URL and may contain input elements, but those input elements get turned into a query string.

How can I get a form to also send along data in the body of the HTTP POST request that it sends when its submit button is pressed?

like image 916
Shaggy Frog Avatar asked Jun 04 '10 02:06

Shaggy Frog


1 Answers

The HTTP spec says that a POST request can contain an arbitrary body of data.

That's correct. There are in turn however several specifications of the format of that data. In case of HTML forms, most commonly used is application/x-www-form-urlencoded, followed by multipart/form-data. You can set it via the enctype attribute of the HTML <form> element. See also chapter 17.13.4 Form Content Types of the HTML specification.


An HTML form element can POST to a URL and may contain input elements, but those input elements get turned into a query string.

That's indeed how application/x-www-form-urlencoded works. Do note that this query string actually represents the whole HTTP request body! So the request body is definitely not empty as you seem to think.


How can I get a form to also send along data in the body of the HTTP POST request that it sends when its submit button is pressed?

It thus actually already does that. If you intented to send a copy of the HTML DOM tree representation of the form itself, as somewhat hinted in the previous statement, then you can achieve that with a little help of JavaScript as follows:

<form onsubmit="this.source.value=this.outerHTML">
    ...
    <input type="hidden" name="source" />
    <input type="submit" />
</form>

The whole HTML DOM tree representation of the form is then in string format available as request parameter with name source.

like image 55
BalusC Avatar answered Sep 30 '22 11:09

BalusC