Sending a POST Request


XMLHttp.setRequestHeader("Content-type",   "application/x-www-form-urlencoded"); XMLHttp.send("word1=JavaScript&word2=Phrasebook"); 

When a GET request is being sent, all parameters are part of the URL. For POST, however, this data is sent in the body of the HTTP request. To do that with the XMLHttpRequest object, the parameters must be provided in the send() method. There is one caveat, though: If you want to access these parameters on the server side, the correct Content-type HTTP header must be set. This is done by using the setRequestHeader() method in the following fashion:

Sending a POST Request (xmlhttppost.html)

<script language="JavaScript"   type="text/javascript" src="/books/3/490/1/html/2/xmlhttp.js"></script> <script language="JavaScript"   type="text/javascript"> var XMLHttp = getXMLHttp(); XMLHttp.open("POST", "post.php"); XMLHttp.onreadystatechange = handlerFunction; XMLHttp.setRequestHeader("Content-type",   "application/x-www-form-urlencoded"); XMLHttp.send("word1=JavaScript&word2=Phrasebook"); function handlerFunction() {   if (XMLHttp.readyState == 4) {     window.alert("Returned data: " +                  XMLHttp.responseText);   } } </script> 

The script posts to the URL post.php, which is a simple PHP script just returning the data:

The Target PHP Script of the POST Request (post.php)

<?php   if (isset($_POST['word1']) &&       isset($_POST['word2'])) {     echo $_POST['word1'] . ' ' . $_POST['word2'];   } else {     echo 'No data sent.';   } ?> 

Of course, you can provide any other script in any other server-side technologyor you just POST to a plain text file.




JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net