Thursday, September 01, 2005

AJAX: Usable Interactivity with Remote Scripting [JavaScript & DHTML Tutorials]

AJAX: Usable Interactivity with Remote Scripting [JavaScript & DHTML Tutorials]:

Transporting Data using an XMLHttpRequest Object

Once an XMLHttpRequest object has been created, we must call two separate methods in order to get it to retrieve data from a server.

open() initialises the connection we wish to make, and takes two arguments, with several optionals. The first argument is the type of request we want to send; the second argument identifies the location from which we wish to request data. For instance, if we wanted to use a GET request to access feed.xml at the root of our server, we'd initialise the XMLHttpRequest object like this:

requester.open("GET", "/feed.xml");

The URL can be either relative or absolute, but due to cross-domain security concerns, the target must reside on the same domain as the page that requests it.

The open() method also takes an optional third boolean argument that specifies whether the request is made asynchronously (true, the default) or synchronously (false). With a synchronous request, the browser will freeze, disallowing any user interaction, until the object has completed. An asynchronous request occurs in the background, allowing other scripts to run and letting the user continue to access their browser. It's recommended that you use asynchronous requests; otherwise, we run the risk of a user's browser locking up while they wait for a request that went awry. open()'s optional fourth and fifth arguments are a username and password for authentication when accessing a password-protected URL.

Once open() has been used to initialise a connection, the send() method activates the connection and makes the request. send() takes one argument, allowing us to send extra data, such as CGI variables, along with the call. Internet Explorer treats it as optional, but Mozilla will return an error if no value is passed, so it's safest to call it using:

requester.send(null);

To send CGI variables using the GET request method, we have to hardcode the variables into the open() URL:

requester.open("GET", "/query.cgi?name=Bob&email=bob@example.com");
requester.send(null);

To send CGI variables using the POST request method, the CGI variables can be passed to the send() method like so:

requester.open("POST", "/query.cgi");
requester.send("name=Bob&email=bob@example.com");

Once we've called send(), XMLHttpRequest will contact the server and retrieve the data we requested; however, this process takes an indeterminate amount of time. In order to find out when the object has finished retrieving data, we must use an event listener. In the case of an XMLHttpRequest object, we need to listen for changes in its readyState variable. This variable specifies the status of the object's connection, and can be any of the following:

* 0 – Uninitialised
* 1 – Loading
* 2 – Loaded
* 3 – Interactive
* 4 – Completed

Changes in the readyState variable can be monitored using a special onreadystatechange listener, so we'll need to set up a function to handle the event when the readyState is changed:

requester.onreadystatechange = stateHandler;
SITEPOINT BOOKS
"DHTML Utopia: Modern Web Design Using JavaScript & DOM"
Photo of Stuart Langridge
by Stuart Langridge
"As the Web becomes a major - if not the major - application development platform, there’s a greater need to give Websites the flexibility and power that client-side applications can provide."
Create usable, slick, and interactive Websites.
Download button Download the free sample now!

readyState increments from 0 to 4, and the onreadystatechange event is triggered for each increment, but we really only want to know when the connection has completed (4), so our handling function needs to realise this. Upon the connection's completion, we also have to check whether the XMLHttpRequest object successfully retrieved the data, or was given an error code, such as 404: "Page not found". This can be determined from the object's status property, which contains an integer code. "200" denotes a successful completion, but this value can be any of the HTTP codes that servers may return. If the request was not successful, we must specify a course of action for our program:

function stateHandler()
{
if (requester.readyState == 4)
{
if (requester.status == 200)
{
success();
}
else
{
failure();
}
}

return true;
}

Even though the XMLHttpRequest object allows us to call the open() method multiple times, each object can really only be used for one call, as the onreadystatechange event doesn't update again once readyState changes to "4" (in Mozilla). Therefore, we have to create a new XMLHttpRequest object every time we want to make a remote call.
Parsing the Data in an XMLHttpRequest Object

If we've made a successful request, two properties of the XMLHttpRequest object may contain data:

* responseXML stores a DOM-structured object of any XML data that was retrieved by the object. This object is navigable using the standard JavaScript DOM access methods and properties, such as getElementsByTagName(), childNodes[ ] and parentNode.
* responseText stores the data as one complete string. If the content type of the data supplied by the server was text/plain or text/html, then this is the only property that will contain data. A copy of any text/xml data will be flattened and placed here as an alternative to responseXML.

Depending upon the complexity of the data, it may be easier to return data simply as a plain text string, thereby making the XML in XMLHttpRequest redundant. However, for more complex data types, you'll probably want to use an XML format, such as this:



John Smith
john@smith.com


We are able to access different parts of the data using standard DOM access methods. Remember that data contained between tags is considered to represent child text nodes of the parent, so we have to take that extra layer of structure into account when we retrieve the data:

var nameNode = requester.responseXML.getElementsByTagName("name")[0];
var nameTextNode = nameNode.childNodes[0];
var name = nameTextNode.nodeValue;

We must also be careful about whitespace: indenting values in the XML file may produce unwanted whitespace in the value, or add additional text nodes.

Once we've parsed the data from the XMLHttpRequest object, we're free to change, delete and write it onto our Web page as we see fit!
An Example Remote Scripting Application

In order to demonstrate how to use the XMLHttpRequest protocol inside a remote scripting application, I've created a simple, one-page example. It assumes that JavaScript and XMLHttpRequest are available in order to make the code more readable, but in any real-world application, you should always check that XMLHttpRequest is available and have a fallback (i.e. normal form submission) where it is not.

The example application will allow the user to send a free ecard to a friend's email address. To do this, the user has first to enter a receipt number, which they received when they purchased goods previously, and which has since been stored in the database of ExampleCo. Then, the user must complete the remaining fields before the ecard is sent, entering the recipient's email address, the message, and the graphic image that will be used for the card

0 Comments:

Post a Comment

<< Home