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.
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.
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>"; ?>
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.