AJAX 101 – part 1
AJAX, an acronym for Asynchronous JavaScript and XML, is a group of technologies combines to accomplish powerful new forms of the web interactions. It’s composed of JavaScript, the XMLHTTPRequest object and XML, JSON, (X)HTML or even plain text.
Asynchronous means that you can make an HTTP request to a server and continue to process other data while waiting for the server’s response. For example, you can make requests to a server-side script to retrieve data from a database as XML, send data to a server-side script to be stored in a database or simple load a static XML file to populate pages of your web site without ever refreshing the page.
Behind the scenes data transfers are accomplished through the XMLHTTPRequest object, which is the heart of the AJAX engine, as it’s used to exchange data asynchronously with a server-side language, XML or other text format. It combines with the DOM (Document Object Model) to display the AJAX response data as (X)HTML and CSS.
The DOM is a language-independent interface that makes common web page elements accessible through scripting languages. This is extremely useful when working with dynamic data, such as an AJAX response, because it can be parsed by JavsScript and added to page elements on the fly without a browser refresh.
In 1999, Microsoft brought the XMLHTTPRequest object to the web with the release of IE 5.0 as an ActiveX object that was available through JavaScript and VBScript. Since its creation, Mozilla and Apple and Opera have included it in their browsers as well (as a native object).
AJAX is a valuable connection between the interface and backend logic, enabling the backend to be robust and powerful with a simpler, yet intuitive interface that provides as on demand feedback to users. It also provides ways to exchange data with server-side languages and to store it in databases without disconnecting the user from the application, such as standard applications do when refreshing the browser window.
The AJAX Engine
The standard AJAX engine is based on the technologies that make up the acronym: the asynchronous functionality sends requests to a server, which are a type of two-way time delayed communication, enabling data to respond when it’s ready; JavaScript, which creates the object and makes the request and XML, could actually be XML, JSON (JavaScript Object Notation) or any other text format that the server returns as a response to the request.
The data that is returned could be a static file that’s updated by hand or can be a server-side script that returns database data in XML, JSON or another text format.
The standard AJAX engine is fairly simple and easy to learn, especially with prior knowledge of JavaScript and XML. The easiest way to create the AJAX engine is by adding a separate JavaScript file to your project and pointing to it from your (X)HTML.
This file will include all the methods (or functions) that make up this request. Here is how you make the request from your (X)HTML page.
<title> Introduction to Ajax </title> <script type="text/javascript" src="js/request.js"></script> </head> <body onload="javascript :makeRequest (‘path to…/filename’);"> <div id= "body"></div> </body>
Notice that we’re pointing to the JavaScript source, called request.js in the script tag. This file will include the AJAX code.
When the page loads, you need to pass the path of the file that you’re requesting to a method that handles the request. This method, named makeRequest, will receive the path to the requested file and create the XMLHTTPRequest object:
if (window.XMLHttpRequest) { // IE7, IE8, Mozilla, Safari, etc. request = new XMLHttpRequest () ; } else if (window.ActiveXObject) { // IE 6 and previous try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } sendRequest (url) ; }
Internet Explorer 6 and before use the ActiveX object, while the more current Internet Explorer versions 7 and 8, as well as Firefox, Opera, and Safari all use the XMLHttpRequest object.
The URL parameter is the path that we passed to the method when the page loaded, this parameter is passed to the sendRequest method to complete the request:
function sendRequest (ur) { request.obreadystatechange = onResponse; request.open ("GET", url, true); request.send(null); }
The sendRequest method uses the request object that was created in the previous method and triggers three additional method calls which are intrinsic to the request object. The first is the onreadystatechange, which sets the callback method that we’ll create to handle the response of the request.
The second is the open method, which included the HTTP request method, the URL or path to the file that we want to request and a Boolean (a true/false value) defining whethr the call is asynchronous, with true meaning asynchronous.
Lastly, the send method takes additional parameters that can be sent as a query string to a server-side script.
Once the request has been made and the server returns a response, we need to check the readyState of the object to determine if the response has been completely loaded. The readyState included four states: zero is Uninitialised, one is Loading, two is Loaded, three is Interactive and four is Complete.
When the response is fully loaded the HTTP status code will equal 200, which means that the response data can then be accessed successfully. Below is an example of the checkReadyState method, which handles the different states:
function checkReadyState (obj) { if (obj.readyState == 0) { // uninitialized } if (obj.readyState == 1) { // loading } if (obj.readyState == 2) { // loaded } if (obj.readyState == 3) { // interactive } if (obj.readyState == 4) { // complete } if (obj.status == 200) { // successfully loaded return true: } else { return "There was a problem retrieving the XML."; }
As you can see, this method handles all the ready states and has the ability to display a custom message for each state. Once the state equals four, meaning that it has been fully loaded, the request status is checked. If it equals 200, the object has been successfully loaded and we can return to tell the response handler to process the data. If no custom error message is displayed.
This example only displays one message for all errors, but there are many HTTP states available, which are outlined by the World Wide Web Consortium and can be found on its web site (www.w3c.org).
Once the response data has been successfully loaded it’s ready to be parsed. There are two intrinsic methods for retrieving the response data, called ‘responseText’ and ‘response XML’. The responseText method handles all text formats and can be used as a way to debug the response data. Here’s an example for loading HTML data:
<b> This is the header </b><br/> This is the body
This is a simple sample, but it shows that the HTML tags can be used in the response file and that they’ll render properly in requests. Using responseText to retrieve the data is as easy as using the following syntax in the callback method that we set in the (X)HTML page:
function onResponse () { if (checkReadyState(request)) { document.getElementById('body').innerHTML = request.responseText; } else { document.getElementById('body').innerHTML = checkReadyState(request) ; }
This method displays the data or error message as a HTML tag. This works well when displaying plain text or (X)HTML, but if the request is JSON we need to evaluate the response and parse its properties. Here’s an example of the JSON data format:
{‘header’ : ‘This is the header’, ‘body’: ‘This is the body’ }
The data is separated into two sections, the name and the value, by a colon. Additional data is separated by commas into new name/value pairs. Now that we know what the JSON format looks like, this is how we parse it as a response:
function onResponse () { if(checkReadyState(request)) { eval("var response = (" +request.responseText+")"); document.getElementByID(‘body’).innerHTML = "<br>" + response.header + "</b><br/>" response.body; }
The first thing to do when we receive the JSON data is evaluate and give it a name, this creates a JavaScript object from the data by the name that we gave it. Once we have the object created, we can call the properties of the object by name. for example, response.header gives us the value of the header.
The responseText is useful for all text formats, but when we want to parse XML we need to use the reponseXML method, which returns an XML object from XML response data. This object can be accessed by first targeting its root element with the following code:
var response = request.responseXML.documentElement;
Once the root has been targeted properly the elements in the XML can be targeted by name and displayed in the page:
var header = response.getElementByTagName('header')[0].firstChild.data; document.getElementById('copy').innerHTML = header;
The standard AJAX engine is simple to create once you understand the different parts of the process. The only downfall is that you can have different versions of the request in multiple projects and this can become a hassle.
An object-oriented solution helps to avoid issues regarding redundant code, and will provide a more powerful engine. This will be dicussed in part 2 of this post.






Rather interesting. Has few times re-read for this purpose to remember. Thanks for interesting article. Waiting for trackback