- Initializing an AJAX Application
- Sending a GET Request
- Sending a POST Request
- Sending a Synchronous Request
- Receiving Multiple Data from the Server
- Aborting an HTTP Request
- Retrieving HTTP Headers
- Receiving XML from the Server
- Using JSON for Data (De)Serialization
- Creating a Waiting Screen
- Solving the Bookmark Problem
- Solving the Back Button Problem
- Using XSLT
- Using an XML Library
- Using the Yahoo! Web Service
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="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 technology—or you just POST to a plain text file.