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.

http://www.url.net/


ajax logo

About

  • A collection of technolgies (that all pre-existed the name Ajax) used together to enhance user interaction on the WWW and support "Rich Internet Applications".

  • The technologies for Ajax include: JavaScript, Document Object Model (DOM), XML, Cascading Style Sheets (CSS), XMLHttpRequest object.

  • The technology and methodology was used prior to 2005, but in 2005/2006 the idea was popularised through Google (in Google Maps and Gmail) and was named Ajax by Garrett.

  • An acronym Asynchronous JavaScript and XML.

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.

Ajax dataflow
A traditional exchange between client and web server is shown at left.

  • The client sends a request for a document.

  • The web server checks its file system / data-store for the requested info., possibly executes a script and returns an entire XHTML / CSS document.

  • Whilst the server is responding, the client is blocked, waiting for the reply... and wasting the user's time as well as breaking interaction with a site into act-wait-act-wait steps as pages are received and re-rendered by the client.
An Ajax-styled session is also illustrated.

  • The client sends an asynchronous request for a small amount of info. (typically only a small part of a web page that needs updating) to the server by activating JavaScript code.

  • This request is sent via the Ajax engine to the server in the background whilst the user continues to interact with the web page.

  • The server processes the request, synthesises its response (often but not always XML data) and sends it back to the Ajax engine.

  • The Ajax engine converts the data into XHMTL / CSS and updates the part of the web-page that needs updating.

  • The user can continue to interact with the web page during the whole process.

Example: Building a simple Ajax interaction

Phase 1. A WWW form

About this form.

<form name="form1" method="" action="">
<p>
<label>Victorian postal code:
<input name="postcode" type="text" id="postcode" onBlur="getSuburb(this.value);" size="4" maxlength="4" />
</label>

<label> Victorian suburb:
<input name="suburb" type="text" id="suburb" size="50" readonly="readonly">
</label>
</p>
</form>

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",
...[many post codes omitted for clarity]...
);
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.


Return Document Types

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">
<p>
Some text, a <a href="http://www.nerd.com">link</a>, any XHMTL can go in here.
</p>
</div>

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
p = document.createElement("p"); p.innerHTML = "This is an <em>appended</em> paragraph";
document.body.appendChild(p); } </script>
<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.

Google Maps

http://www.ajax.org/#home




This lecture's key point(s):


Courseware | Lecture notes

©Copyright Alan Dorin 2009