KMR Ajax

Title page

Introduction to AJAX

The ability to partially update a web page instead of requiring a complete refresh of that page can be used to give the end user a richer and fuller experience more in-line with what they expect with a desktop application. Ajax is the term being used to claim such is possible with a web application when using the XMLHttpRequest API, JavaScript, and the document object model.

The AJAX acronym flows from the first letters in the group of technologies described as ’ Asynchronous Javascript And XML ’. Over the last few years, this term AJAX has become familiar with many developers of web applications. Google, for example, has implemented both Gmail and Google Maps using AJAX as a core technology. Gmail uses the technology to allow it to update the inbox automatically whenever new mail is received. The end user no longer is required to press the refresh button to check for new mail. Instead, the process is automated for him. Google Maps allow the user to ’ grab ’ the map and move it around the screen where it is updated almost instantly.

Both of these web applications compare favorably with standalone desktop applications in speed of updates and a rich user interaction. Though it has happened gradually, the point is being reached where web applications do not necessarily need to sacrifice responsiveness for mobility and portability.

Much of this success is due to the use of AJAX, yet many developers and other professionals have never been exposed to the technology and cannot really explain what it is, how it is implemented, or what it can be used for.

Classic Web application Model Vs Ajax Model:





Step 1 – How to Make an HTTP Request
In order to make an HTTP request to the server using JavaScript, you need an instance of a class that provides this functionality. Such a class was originally introduced in Internet Explorer as an ActiveX object, called XMLHTTP. Then Mozilla, Safari and other browsers followed, implementing an XMLHttpRequest class that supports the methods and properties of Microsoft ’ s original ActiveX object.

As a result, in order to create a cross-browser instance (object) of the required class, you can do:

var httpRequest;

if (window.XMLHttpRequest) { // Mozilla, Safari, ...

httpRequest = new XMLHttpRequest;

} else if (window.ActiveXObject) { // IE

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

}

Next, you need to decide what you want to do after you receive the server response to your request. At this stage, you just need to tell the HTTP request object which JavaScript function will do the work of processing the response. This is done by setting the onreadystatechange property of the object to the name of the JavaScript function you plan to use, like this:

httpRequest.onreadystatechange = nameOfTheFunction;

Note that there are no brackets after the function name and no parameters passed, because you ’ re simply assigning a reference to the function, rather than actually calling it. Also, instead of giving a function name, you can use the JavaScript technique of defining functions on the fly (called "anonymous function") and define the actions that will process the response right away, like this:

httpRequest.onreadystatechange = function {

// do the thing

} ;

Next, after you ’ ve declared what will happen as soon as you receive the response, you need to actually make the request. You need to call the open and send methods of the HTTP request class, like this:

httpRequest.open( ’ GET ’, ’ http://www.example.org/some.file ’ , true);

httpRequest.send(null);

The parameter to the send method can be any data you want to send to the server if POST-ing the request. The data should be in the form of a query string, like:
 * The first parameter of the call to open is the HTTP request method – GET, POST, HEAD or any other method you want to use and that is supported by your server. Keep the method capitalized as per the HTTP standard; otherwise some browsers (like Firefox) might not process the request. For more information on the possible HTTP request methods you can check the W3C specs
 * The second parameter is the URL of the page you ’ re requesting. As a security feature, you cannot call pages on 3rd-party domains. Be sure to use the exact domain name on all of your pages or you will get a ’ permission denied ’ error when you call open. A common pitfall is accessing your site by domain.tld, but attempting to call pages with www.domain.tld.
 * The third parameter sets whether the request is asynchronous. If TRUE, the execution of the JavaScript function will continue while the response of the server has not yet arrived. This is the A in AJAX.

name=value&anothername=othervalue&so=on

Note that if you want to POST data, you have to change the MIME type of the request using the following line:

httpRequest.setRequestHeader( ’ Content-Type ’, ’ application/x-www-form-urlencoded ’ );

Otherwise, the server will discard the POSTed data.

Step 2 – Handling the Server Response
Remember that when you were sending the request, you provided the name of a JavaScript function that is designed to handle the response.

httpRequest.onreadystatechange = nameOfTheFunction;

Let ’ s see what this function should do. First, the function needs to check for the state of the request. If the state has the value of 4, that means that the full server response is received and it ’ s OK for you to continue processing it.

if (httpRequest.readyState == 4) {

// everything is good, the response is received

} else {

// still not ready

}

The full list of the readyState values is as follows:

The next thing to check is the status code of the HTTP server response. All the possible codes are listed on the W3C site. For our purposes we are only interested in 200 OK response.
 * 0 (uninitialized)
 * 1 (loading)
 * 2 (loaded)
 * 3 (interactive)
 * 4 (complete)

if (httpRequest.status == 200) {

// perfect!

} else {

// there was a problem with the request,

// for example the response may be a 404 (Not Found)

// or 500 (Internal Server Error) response codes

}

Now after you ’ ve checked the state of the request and the HTTP status code of the response, it ’ s up to you to do whatever you want with the data the server has sent to you. You have two options to access that data:


 * httpRequest.responseText – will return the server response as a string of text
 * httpRequest.responseXML – will return the response as an XMLDocument object you can traverse using the JavaScript DOM functions

Step 3 – A Simple Example
Let ’ s put it all together and do a simple HTTP request. Our JavaScript will request an HTML document, test.html, which contains the text "I ’ m a test." and then we ’ ll alert the contents of the test.html file.

< script type="text/javascript" language="javascript" >

function makeRequest(url) {

var httpRequest;

if (window.XMLHttpRequest) { // Mozilla, Safari, ...

httpRequest = new XMLHttpRequest;

if (httpRequest.overrideMimeType) {

httpRequest.overrideMimeType( ’ text/xml ’ );

// See note below about this line

}

}

else if (window.ActiveXObject) { // IE

try {

httpRequest = new ActiveXObject("Msxml2.XMLHTTP");

}

catch (e) {

try {

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

}

catch (e) {}

}

}

if (!httpRequest) {

alert( ’ Giving up :( Cannot create an XMLHTTP instance ’ );

return false;

}

httpRequest.onreadystatechange = function { alertContents(httpRequest); } ;

httpRequest.open( ’ GET ’, url, true);

httpRequest.send( ’’ );

}

function alertContents(httpRequest) {

if (httpRequest.readyState == 4) {

if (httpRequest.status == 200) {

alert(httpRequest.responseText);

} else {

alert( ’ There was a problem with the request. ’ );

}

}

}

< /script >

< span

style="cursor: pointer; text-decoration: underline"

onclick="makeRequest( ’ test.html ’ )" >

Make a request

< /span >

In this example:


 * The user clicks the link "Make a request" in the browser;
 * This calls the makeRequest function with a parameter – the name test.html of an HTML file in the same directory;
 * The request is made and then (onreadystatechange) the execution is passed to alertContents;
 * alertContents checks if the response was received and it ’ s an OK and then alerts the contents of the test.html file.

Step 4 – Working with the XML Response
In the previous example, after the response to the HTTP request was received we used the responseText property of the request object, which contained the contents of the test.html file. Now let ’ s try the responseXML property.

First off, let ’ s create a valid XML document that we ’ ll request later on. The document (test.xml) contains the following:

< ?xml version="1.0" ? >

I ’ m a test.

< /root >

In the script we only need to change the request line to:

...

onclick="makeRequest( ’ test.xml ’ )" >

...

Then in alertContents, we need to replace the line alert(httpRequest.responseText); with:

var xmldoc = httpRequest.responseXML;

var root_node = xmldoc.getElementsByTagName( ’ root ’ ).item(0);

alert(root_node.firstChild.data);

This code takes the XMLDocument object given by responseXML and uses DOM methods to access some of the data contained in the XML document.

Current Use:


 * Since the early induction of AJAX to improve interactivity and user experience in Audible.de, AJAX has been a widely accepted technology to develop rich user friendly applications. AJAX has also been adopted now on other Audible web sites viz. Audible.com, Audible.fr.


 * Audible.com has been using AJAX to load contents like Best Sellers, New Releases etc on the homepage for sometime now. Since AJAX is an asynchronous technology, it helps in improving the performance of the homepage in terms of loading time, as contents on the page are now loaded asynchronously.


 * The Audible Kids web site has also adopted AJAX widely and is using it all across the site.


 * Audible.de was one of the first adopters of AJAX at Audible. AJAX has been widely used at the following places – My Library, Author Narrator Pages, Homepage – Tell A Friend, Wish List. One of the very fine use of AJAX can be seen in the New Registration application which is a Configurable Landing Page system which incorporates User Registration and Buy.

Further Reading:

http://www.dmoz.org/Computers/Programming/Languages/JavaScript/AJAX/

Javascripts:


 * One of the very immediate effects of using AJAX is the requirement of developing and maintaining complex Javascripts. This calls for developing Object Oriented Javascripts. Though it is not necessary to use JS frameworks, using one greatly simplifies the Javascript development. A number of frameworks such as Yahoo UI, Prototype, Scriptaculous, Mootools etc are available in the market to simplify the effort involved in this process. These Javascript Libraries provide a number of custom UI components which can be easily plugged in thus reducing the time involved in implementing UI features. Audible.de uses the Mootools JS Library extensively in the New Reg application. The library provides us a simple API for DOM manipulation, DHTML effects, Browser History management, event handling etc.

Mootools API documentation:

http://docs.mootools.net/


 * Data extraction from XML responses received in an AJAX response can be a cumbersome and error prone task. XML For < SCRIPT > is a simple JS based XML parser which can simplify the XML parsing. XPath can be used to query XML data nodes directly instead of hierarchical DOM parsing.

XML For < SCRIPT > 

http://xmljs.sourceforge.net/

Aptana – The Aptana eclipse plugin can be used for JS editing. It has inbuilt integration for mootools JS library.

Firebug – Firebug is a very effective Firefox plugin which helps greatly in the development of AJAX applications. Important features – Javascript debugging support, Http Console to track http request from the browser including XML Http Requests, on the fly HTML DOM inspection and manipulation, CSS Style manipulation.

New Reg URL - http://http-a00-00.ofc.dev.ewr.audible.de/argon

The following file should give you a good insight into using mootools and making AJAX requests using mootools. It also uses XML For Script for xml parsing using XPath to extract data from the XML responses.

http://http-a00-00.ofc.dev.ewr.audible.de/newregopt/js/landingPage.js