GET vs POST

Should we use the GET method for sending data from an HTML form, or the POST method instead?

GET and POST access methods are defined in the HTTP protocol and included in the HTML specification.
The choice of method depends on how the data is received, the size and nature of the data.

The GET method adds data to the URL

In the form, it is specified as follows:

<form method="get" action="page.html">
</form> 

With this method, the form data will be encoded in a URL. It is composed of the name of the page or script to be loaded, with form data packaged in a string.
The data are separated from the address of the page by the ? code and between them by the & code.

So if you send to page.html, the values "color blue" and " shape rectangle", the URL build by the browser will be:

http://www.xul.fr/page.html?color=blue&shape=rectangle 

The HTML 4 specification calls for the use of GET when the request does not cause any change in the data, then to make a single reading. (Référence).

The form data must be ASCII only. The size of a URL is limited to just over 2.000 characters, including escape codes.

Note that when the user uses the back button, GET requests are re-executed.

The POST method has no size limit

In the form, it is specified as follows:

<form method="post" action="page.php">
</form> 

This method sends a header and a body message to the server. The body usually consists of data entered into the form fields by the user.

The form data do not appear in the URL. Accordingly, it is not possible to retrieve data directly in JavaScript, you should add some PHP code in the page:

<?php
 $color = $_POST['color'];
 $shape = $_POST['shape'];
?>
...  HTML code ... 

You can however assign data retrieved through PHP to a JavaScript script:


<script>
 var color = <?php echo $color;?>;
 var shape = <?php echo $shape;?>;
</script>

Conclusion

The GET method is the default value. It is use it unless you do not want the parameters to be added to the URL. It allows to retrieve data passed to the page with JavaScript code.

The POST method is essential for non-ASCII codes, for large data, and it is recommended to change the data on the server and for sensitive data as explained by the W3C..
When using POST, you must integrate PHP (or other language) on the page where data will be used.

See also

© 2010-2014 Xul.fr