Sunday, January 30, 2011

HTML GET and POST

Let us quickly try to understand GET and POST request in HTML.
GET is used to request data from server and POST is used to submit data to server.

Let us create a simple HTML page called request.html as show below
<html>
    <head>
        <title>
            Request
        </title>
    </head>
    <body>
        <form method="GET" action="response.php">
            Enter the GET METHOD text:
            <input type="text" name="getinput" value="get value"/>
            <br/>
            Enter the POST METHOD text:
            <input type="text" name="postinput" value="post value"/>
            <br/>
            <input type="submit" value="Submit"/>
        </form>
    </body>
</html>
Save request.html file under apache\htdocs folder in c:\ if you have one.

Now create another file called response.php as show below
<?php
echo "GET:".$_GET["getinput"]; //GET
echo "<br/>";
echo "POST:".$_POST["postinput"]; //POST
?>
Save response.php file under apache\htdocs folder in c:\ if you have one.

If you notice the request.html source code the form tag's method attribute is set to GET.
Now open the request.html file using any of your web browser (e.g. http://localhost/request.html).
After the file opens in your web browser, hit the submit button.
Now you can notice the address bar URL had changed to
http://localhost/response.php?getinput=get+value&postinput=post+value
The above URL is also called Query String.
And the response would be
GET:get value
POST:
The above result is because we used GET method to QUERY/POST data to the server.

Now change the method attribute (form tag) value to POST in the request.html file and save the file.

Now again open the request.html file using any of your web browser (e.g. http://localhost/request.html).
After the file opens in your web browser, hit the submit button.
Now you can notice the address bar URL had changed to
http://localhost/response.php
And the response would be
GET:
POST:post value
The above result is because we used POST method to POST data to the server.

Take some time and try to understand the request.html and response.php file source code.
Please read more on Hypertext Transfer Protocol and Query string.

No comments: