Hopefully you have read Part 1 & 2 of this series on AJAX, so you should have a good understanding of how AJAX works. Now we will use a slightly different approach to doing the Asynchronous data send/receive with AJAX; we will use the POST method instead of the GET method!
The advantage of this is primarily security, however you often can send larger amounts of data with the POST method as well (but that is dependant on your server configuration rather it be Apache/PHP, Microsoft/IIS, or Java/J2EE, etc). The primary advantage of POST is again, the security of the communication, because often log files on the web server will log the AJAX GET request data because that data is part of a URL in the request. This does not occur with the AJAX POST request.
AJAX / Post Example
The following JavaScript/HTML example is similar to the Get AJAX method, but you must set some header information before you actually do the AJAX send, and you have to encode your data to send slightly different from the Get method. Additonally, the data to send is not part of the URL of course. This listing will be explained next.
Listing A: JavaScript/HTML page using AJAX / POST request
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>

<title>Advanced AJAX Part 1</title>

<script language="javascript"  type="text/javascript">

function doHttpRequest( ) {  // This function does the AJAX request
 
  //  Set our destination PHP page "ajaxpost.php"…
  http.open("POST", "http://www.jdcampbell.com/ajax/ajaxpost.php", true);
  http.onreadystatechange = getHttpRes;

  // Make our POST parameters string…
  var params = "address=" + encodeURI(document.getElementById("address").value)+
	"&city=" + encodeURI(document.getElementById("city").value)+
	"&state=" + encodeURI(document.getElementById("state").value)+
	"&zip=" + encodeURI(document.getElementById("zip").value);

  // Set our POST header correctly…
  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http.setRequestHeader("Content-length", params.length);
  http.setRequestHeader("Connection", "close");

  // Send the parms data…
  http.send(params);

}

function getHttpRes( ) {
  if (http.readyState == 4 && http.status == 200) { 
    res = http.responseText;  // These following lines get the response and update the page
    document.getElementById('txt1').value = res;
    document.getElementById('cell1').innerHTML = res;
    document.getElementById('cell2').innerHTML = res;
  }
}

function getXHTTP( ) {
  var xhttp;
   try {   // The following "try" blocks get the XMLHTTP object for various browsers…
      xhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e2) {
 		 // This block handles Mozilla/Firefox browsers...
	    try {
	      xhttp = new XMLHttpRequest();
	    } catch (e3) {
	      xhttp = false;
	    }
      }
    }
  return xhttp; // Return the XMLHTTP object
}

var http = getXHTTP(); // This executes when the page first loads.

</script>

</head>

<body>

Enter Address:<input type="text" size="45" name="address" id="address" /><br>
City:<input type="text" size="25" name="city" id="city" />
State:<input type="text" size="5" name="state" id="state" /> 
Zip:<input type="text" size="5" name="zip" id="zip" /> <br>

Fill in above fields and press this...<input type="button" value="AJAX Post" name="btn"  
onClick="doHttpRequest();" >

<br><br><br>

Return data...

<textarea id="txt1" name="txt1" rows="3" cols="30" style="width: 100%">empty</textarea>

<br>

<table width=100% border=1 cellspacing=0>
   <tr><td id="cell1">cell1</td><td id="cell2">cell2</td><tr>
</table>

</body>
</html>
The section above contains all of the code needed to initiate an AJAX Post operationn. The PHP script which handles the AJAX Post operation is shown and explained later. To break it down and explain the above AJAX JavaScript code, let's first look at the following two lines:
http.open("POST", "http://www.jdcampbell.com/ajax/ajaxpost.php", true);
http.onreadystatechange = getHttpRes;
This may look similar to a Get AJAX operation and it is, but with two distinct differences. (1) The http.open statement specifies "POST" and not Get, (2) the http.open statement has a URL which consists of just the address of the PHP server script to handle the Post request, there is no added data/fields to the URL. The second line above is identical to the Get type AJAX request.
Next let's consider the following line from the above page. This line produces a variable named params which contains the data/fields that are Posted to the PHP server script. It is necessary to use the JavaScript encodeURI( ) method to escape any strange characters in our data fields. You will notice how we reference all of our data fields by ID using methods like document.getElementById("address").value, shown below. This operation of producing the params variable is different then the AJAX Get operation because, as you will remember with the Get operation, we actually concatenate the data fields onto the URL of the http.open( ) statement above, but with the Post operation the data fields are in a variable independently.
var params = "address=" + encodeURI(document.getElementById("address").value)+
	"&city=" + encodeURI(document.getElementById("city").value)+
	"&state=" + encodeURI(document.getElementById("state").value)+
	"&zip=" + encodeURI(document.getElementById("zip").value);
It is important to note that we create our params variable (shown above) before the following lines; this is because the second line below: http.setRequestHeader("Content-length", params.length), actually references the size of our params variable so it can be set in the Http headers before sending the AJAX request.
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
The final line in our AJAX Post function just initiates the AJAX Post operation. Notice that we specify the Post data which is the params variable.
http.send(params);
PHP Script "ajaxpost.php", the Server-side
The PHP script which you use to handle an AJAX Post request must use the $_POST[ ] server variables to get the Post data fields from the client-browser. Here is an example which works with our example AJAX HTML page above.
Listing B: PHP Script to handle the AJAX/Post request
<?

echo "PHP Processed this data on server:<br>";
echo $_POST["address"]."<br>";
echo $_POST["city"].", ".$_POST["state"]." ".$_POST["zip"]."<br>";

?>
You can save the above on your PHP server as "ajaxpost.php" and use it with the JavaScript/HTML page in listing #A above.
That about wraps it up for AJAX Post operations. You can use XML documents in AJAX Post communication just like Get communication operations. You simply use the http.responseXML.documentElement method to get your data on the AJAX receiving data function that you define; this was shown in Part 2 of this AJAX series. We will have our next article in this series on AJAX next week, so check back with us soon.