Thursday, September 14, 2006

AJAX Anatomy

Anatomy of an AJAX Transaction

In case you've heard all the AJAX hype but still haven't seen a good, simple technical explanation of what AJAX really is.. look no further.

As a small New Years gift, here is a brief write up on the core technology that makes AJAX possible.

In order to present AJAX in its purest form, I'll just provide a basic AJAX only example without mixing it with other technologies such as JSF, JSP etc. (I'll show that later..)

First of all, is AJAX New?

Not really. Remote Javascript, of which AJAX is one example of, has garnered the most attention as of late, provides the ability to interact with a server with XML data. AJAX is possible because of the leading browsers now offering objects that can make independent XML HTTP requests. Internet Explorer 5 and later offer an XMLHTTP object while Mozilla based browers provide an XMLHttpRequest object. Both of these objects offer essentially the same ability to request XML data from a server and process the data in a similar fashion. The server-side AJAX component can be in any technology providing XML can be delivered dynamically. Any dynamic Web technology ranging from PHP to servlets can serve as an AJAX server.

One of the drawbacks to Remote Javascript and AJAX is that it forces the page author (the person designing the final page) to develop a fair amount of Javascript code that manages the XMLHTTP interactions. Fortunately this is where JavaServer Faces provides a solution and makes AJAX very easy to use.
AJAX Under The Hood

Before reviewing more advanced examples of AJAX enabled JSF components, it is useful to full understand the core AJAX architecture involved in an AJAX client-server transaction.

AJAX is possible providing the two core technologies are present:

* A Javascript enabled browser that supports either XMLHTTP or XMLHttpRequest objects.
* An HTTP Server technology that can respond in XML.

Since the popular browsers support Javascript and the necessary XMLHTTP request objects and almost any Web server technology can generate XML(or any markup), the core AJAX technology is widely available.

An AJAX application in its simplest form is essentially a standard HTML user interface with Javascript functions to interact with an HTTP server that can generate XML dynamically. Any dynamic Web technology ranging from CGI to servlets even including JavaServer Faces as we’ll review later, can serve as a server-side AJAX technology.

The key elements of a core AJAX application are:

* An HTML page that contains:
o UI elements that interact with AJAX Javascript functions
o Javascript Functions that interact with AJAX server.
* A server-side Web technology that can process HTTP requests and respond in XML markup.

Reviewing the key elements, we have an HTML user interface with elements such as an input field, a button or anything that can be linked to Javascript. For example a button could fire a Javascript function when pressed, or for even more subtle usage an input field could fire a Javascript function as the user types into the field. For this an “onkeyup=” could be set to the value of the Javascript function to process the data in the input field. For example the input field “searchField” will call the Javascript function “lookup( )” when an onkeyup events occur (i.e. during typing).

<input type="text" id="searchField" size="20" onkeyup="lookup('searchField');">

In addition to responding to user interface interactions (like typing), AJAX Javascript functions they can operate independently on their own timers. (An AJAX autosave feature can be implemented using this approach.)
How to issue an XML HTTP Request

Now that we’ve reviewed how the AJAX Javascript code can be invoked, let’s review the actual code in Javascript that can issue an XML HTTP request:

if (window.XMLHttpRequest) {

req = new XMLHttpRequest();

}

else if (window.ActiveXObject) {

req = new
ActiveXObject("Microsoft.XMLHTTP");

}

This code snippet allows both major browser families (Internet Explorer and Mozilla/Safari) to make independent HTTP requests to servers. This code first checks to see if the browser supports either of the supported XMLHTTP objects and then instantiates one.

Once an XMLHttpRequest (or Microsoft’s XMLHTTP) object has been instantiated, it can be operated on in exactly the same manner.

To initialize a connection to a server, the open method is used:

req.open("GET", url, true);

The first argument is the HTTP method (GET or POST). The second argument is the URL of the server (or form action is using a POST) and the third argument when true denotes whether the call should be made asynchronously (The “A” in AJAX). This means that the browser can continue doing other things while the request is being fulfilled. A false value in the open method denotes a non-asynchronous or serial processing. This is not recommended, since your browser will cease operations until the response has been returned.

After initializing a connection using open, the onreadystatechange call is made (only for asynchronous calls). This registers a callback function, which will be invoked once the request is complete:

req.onreadystatechange = processXMLResponse;

The function processXMLResponse( ), which processes the XML response, is invoked when the request is fulfilled. A callback function can also declared inline in the onreadystatechange statement:

req.onreadystatechange = processXMLResponse() {

// process request

};

Any header content can also be specified using req.setRequestHeader. Such as:

req.setRequestHeader(“Cookie”, “someKey=true”);

Once the XMLHTTP request object (req) has been fully initialized, initiating a call to the server can be done using send( ):

req.send(null);

For GET requests, a null value or empty string “” is used.

POST requests contain a string argument with form data. They also require the Content-Type to be set in the header of the request. The following two lines show how to perform a AJAX POST request.:

req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded";

req.send(“name=scott&email=stiger@foocorp.com”);

The callback function, which is called once the request has been fulfilled, usually has some code to make sure the request has not error-ed out. This can be accomplished by checking the readyState as well as the overall status of the HTTP request. (A readystate of 4 means the XMLHTTP request is complete and 200 means it was a success (as opposed to 404 etc..)

function processXMLResponse() {

if (xmlreq.readyState == 4) {

if (xmlreq.status == 200) {

// Process the XML response…

}

}

}

Processing the XML response is done using standard Javascript DOM methods. For example to extract the employee name from the incoming XML stream:

Chirag

one can use the following:

var name = req.responseXML.getElementsByTagName("employee")[0];

Parsing more complex XML involves iterating through the elements using code such as:

for (i=0;i
for (j=0;j
var ElementData = elements[i].childNodes[j].firstChild.nodeValue;

}

}

No comments: