FIT3084: AJAX : Asynchronous JavaScript and XML
In the previous lecture:
In this lecture:
References
Sebasta, R.W., "Programming the WWW 2009", 5th edition, Pearson, chapter 10.
About
|
How does Ajax work? Ajax is a way of using a collection of existing technologies to improve the rate at which a user can interact with a web page. Ajax is not a langage or API. |
|
A traditional exchange between client and web server is shown at left.
|
An Ajax-styled session is also illustrated.
|
Example: Building a simple Ajax interaction
Phase 1. A WWW form
About this form.
<form name="form1" method="" action=""> |
Phase 2. JavaScript handler for the asynchronous event
<script language="JavaScript"> function getSuburb(code) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if ((xhr.readyState == 4) && (xhr.status == 200)) { var result = xhr.responseText; document.getElementById("suburb").value = result; } } var callString = "http://www.csse.monash.edu.au/~cema/cgi-bin/getSuburbFromCode.cgi?postcode=" + code; xhr.open("GET", callString, true); xhr.send(null); } </script> |
JavaScript analysis.
We make a new XMLHttpRequest object that is used to:
xhr = new XMLHttpRequest(); |
Skipping down the code a little... we assemble the string that corresponds to the CGI script name.
We will call the CGI script using the GET method, so the string must include parameters after a "?".
var callString = "http://www.csse.monash.edu.au/~cema/cgi-bin/getSuburbFromCode.cgi?postcode=" + code; |
We use the XMLHttpRequest object's method:
xhr.open("GET", callString, true); xhr.send(null); |
Backtracking through the code a little...
The XMLHttpRequest object triggers a readystatechange event if its readyState property's value is changed.
The XMLHttpRequest object has a property onreadystatechange that must point to a method to handle the these changes.
Here we set the event handler to be an internal function() without a name.
xhr.onreadystatechange = function () { ... } |
The function() will be called multiple times as the server handles the request and updates the object's readyState property.
XMLHttpRequest.readyState values | |
0 | XMLHttpRequest has been created but not yet uninitialised |
1 | XMLHttpRequest.open() has been called and object is ready to send |
2 | XMLHttpRequest.send() has been called but no response received |
3 | XMLHttpRequest has received the HTTP response headers but not the complete message body |
4 | XMLHttpRequest has received all header and body information |
The value that tells us that the request has been completed is readyState==4.
The XMLHttpRequest object's status property is set by the server to the HTTP status code.
E.g. 200 (OK) or 404 (Not Found). The value of this property is undefined if readyState<3.
if ((xhr.readyState == 4) && (xhr.status == 200)) { ... } |
If the request was completed successfully, the XMLHttpRequest object holds the response text.
In our example, we insert this into the value attribute of the suburb text entry box.
var result = xhr.responseText; document.getElementById("suburb").value = result; |
3. PHP script.
In: post code parameter
Out: corresponding suburb's name
#!/usr/local/bin/php <?php $suburbArray = array( "3000" => "Melbourne Melbourne", "3001" => "Melbourne Melbourne", "3002" => "Melbourne East Melbourne", "3003" => "Melbourne West Melbourne", "3005" => "Melbourne World Trade Centre", "3006" => "Melbourne Southbank", header("Content-type: text/plain;"); $postcode = $_GET["postcode"]; if (array_key_exists($postcode, $suburbArray)) { print $suburbArray[$postcode]; } else { print "unrecognised postcode"; } ?> |
Note that the Content-type returned by this script is text/plain. This is not always the case (see below).
Otherwise this PHP program is a normal CGI scrip that can be executed as normal:
http://www.csse.monash.edu.au/~cema/cgi-bin/getSuburbFromCode.cgi?postcode=3000
Working with Microsoft Internet Explorer 5 & 6.
Microsoft's Internet Explorer 5 & 6 web browsers do not employ the XMLHttpRequest object.
Instead, they employ an ActiveXObject called XMLHTTP.
For compatability with all browsers therefore, replace the object creation code above with:
if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = newActiveXObject("Microsoft.XMLHTTP"); } |
Apart from this, all browsers will operate in the same way.
1. Plain text return document type.
2. XHTML return document type.
Suppose we have a <div> tag in the current document like this:
<div id="replaceableXHTML"> |
If a script generates some XHMTL that is returned via XMLHttpRequest.responseText:
<p>Some different text.</p> <ul> <li>a list element</li> <li>another list element</li> </ul> <p>Some other XHMTL can go in here.</p> |
The initial text in the <div> tag can be substitued for the returned text:
document.getElementById("replaceableXHTML").innerHTML = xhr.responseText; |
Here is the method in action (see method replaceText() in the <head> of this document)...
Here is some replaceable text in a <div> tag. |
3. XML return document type.
We don't cover XML during this unit but you still need to understand a few things since the X in Ajax refers to XML...
Writing parsers for XML (to create XHTML) is a little complex and error prone.
If the structure of the existing document matches the structure of the returned XML, after the XML is parsed, the existing document's components can be swapped using the innerHTML property as in the example above.
Otherwise, DOM methods such as createElement() and appendChild() can be used to generate new XHTML document objects once the XML has been parsed.
<html> <head> <title>Creating elements</title> </head> <script type="text/javascript"> var theOriginalDiv = null; var newDiv = null; var p = null; function addElements() { // create a new div element and give it some content newDiv = document.createElement("div"); newDiv.innerHTML = "<h1>This is a heading!</h1>"; // add the newly created element and it's content into the DOM theOriginalDiv = document.getElementById("originalDiv"); document.body.insertBefore(newDiv, theOriginalDiv); // Create a new paragraph element, and append it to the end of the document body <body onload="addElements()"> <div id='originalDiv'> The heading above was generated dynamically.</div> </body> </html> |
View this example in a web browser.
Advanced Ajax examples.
©Copyright Alan Dorin 2009