JOIN
Get Time
features   
Discuss this article
An Introduction to AJAX


By 39inam
TopCoder Member

AJAX (Asynchronous JavaScript and XML) is the latest boom in the Web development world. AJAX helps developers narrow the gap between desktop and web applications — Google Earth, Flicker and MS Outlook Express Web Version are some of the applications powered by AJAX. This article will explore the basics of AJAX programming and then build on it using practical examples. For this article, I am assuming that readers have a basic understanding of JavaScript, DOM (Document Object Model) and XML.

Introduction
Want to read more on AJAX? Check out this presentation TopCoder's Andy LaMora gave at the TCO, in which he traces the development of user interface paradigms over the years and looks at the future of AJAX. Also, you can read DPlass' blog entry on the presentation.
AJAX is not a new technology; it is basically a web development technique which uses existing technologies like JavaScript and XML. So you can actually start working in AJAX if you have a basic understanding of above mentioned technologies.

Asynchronous means that you can make a request to a server and perform other actions while the server is processing your request -- and on the arrival of the response required actions can be performed -- as opposed to conventional web applications, in which the user has to sit back and stare at the blank screen while the server is processing the request. Therefore using AJAX will improve the interactivity of your web application.

In conventional web applications when a user makes a request to the server the whole page is reloaded, while AJAX applications only update the relevant portion.

Let's look at an example

Figure 1


A book shop website is shown in the figure above. To view the books in a specific category, a user selects the category and the related books are shown in the area below. In the conventional web applications the whole page would be reloaded, but in the case of AJAX only the relevant portion is updated (as shown in the figure below).

Figure 2


AJAX Architecture


Figure 2


AJAX architecture is very simple; a user makes an initial request and, in response, the page with the AJAX engine is loaded. Thereafter, the user sends all requests to the AJAX engine through JavaScript function calls, while the AJAX engine forwards requests to the server, parses the responses, and displays the HTML in the browser.

Let's take another look at the book shop example:

Normal scenario - When the user selects a particular category the request is sent to the server. In return, a new page with book details is loaded to the browser.

AJAX - When a user selects a particular category the AJAX engine is called, which sends the request to the server using XmlHttpRequest object, parses the response, and updates the relevant portion of the page -- therefore the whole page is not reloaded.

AJAX engine
AJAX engine is nothing but some simple JavaScript functions which use XmlHttpRequest object to make requests to the server. XmlHttpRequest is the main player in an AJAX application it handles all the communication with the server.

Common methods and properties of XmlHttpRequest Object

Property Description
onreadystatechange Event handler that fires when the state of the request object changes.
readyState Returns values that indicate the current state of the object.
responseText String version of the response from the server.
responseXML DOM-compatible document object of the response from the server.
status Status code of the response from the server.
statusText Status message returned as a string.


Method Description
Abort() Cancels the current HTTP request.
getAllResponseHeaders() Retrieves the values of all the HTTP headers.
getResponseHeader("headerLabel") Retrieves the value of an HTTP header from the response body.
open("method", "URL"[, asyncFlag[, "userName"[, "password"]]]) Initializes an MSXML2.XMLHTTP request, specifying the method, URL, and authentication information for the request.
send(content) Sends an HTTP request to the server and receives a response.
setRequestHeader("label", "value") Status message returned as a string.


AJAX Explanation

Steps Involved
  1. Get the form data.
  2. Make a request to the server.
  3. Get and parse Response.
  4. Update the relevant portion.
Let's consider the book shop example. First, we will attach an event with the drop down list
<select onChange="showbooks()" accesskey="cat" size="1" id="category" name="category">
       <option value="History">History</option>
       <option value="Computer Science">Computer Science</option>
       <option value="Politics">Politics</option>
       <option value="Commerce">Commerce</option>
       <option value="Law">Law</option>
       </select>
In the above example I attached a JavaScript function "showbooks" (I will explain it later) with onChange event of dropdown list named category. Whenever a user selects a different option the showbooks() function would be called. This function, basically, is our AJAX engine

Showbooks function

This function has to perform following tasks
  1. Create a XmlHttpRequest Object
  2. Grab the selected category
  3. Build the request URL
  4. Make the request
Creating the XmlHttpRequest object:
var xmlHttp = false;
if (@_jscript_version >= 5) 
try {
  xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
  try {
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (e2) {
    xmlHttp = false;
  }
}

if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
  xmlHttp = new XMLHttpRequest();
}
Create a reference to XmlHttpRequest Object and assign it to XmlHttp. For MS Internet Explorer 5.0 or above version reference can be obtained by:
 xmlHttp =ActiveXObject("Msxml2.XMLHTTP ");
For other IE versions it can be obtained by:
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
For all other browsers it can be obtained by:
xmlHttp = new XMLHttpRequest();
Grabbing the selected category:
var cat= document.getElementById("category").value;
Building the request URL:
var url = "getbooks.php?cat=" + escape(cat);
escape(cat) is a javascript function, which encodes the string provided as argument. It encodes all that characters which can't be transferred in the request.

For example, if a space occurs it is encoded as "%20" because it can't be transferred in the request URL.

Making the request:
    xmlHttp.open("GET", url, true);
A connection is opened and the method of connection is specified, i.e. "Get" next argument is the url and last argument specifies the Boolean value, whether you want the request to be asynchronous or not.

An event handler is specified, which will fire every time the state of the request object is changed. This event handler is a very good place for error handling, as well as for providing the user with feedback. I will explain the onreadystatechange event later.
   xmlHttp.send(null);
Next the request is made through send() method. The only argument of the send() method is a query string. Since we are using "Get" method we don't need to specify the query string.

Parsing the Response
function updatepage()
{
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{
var response= xmlHttp.responseText;
}

document.getElementById("detail").innerHtml=response;
}
readystate=4 means that the server has completed the processing of request and the object is completely intilialized. responseText is the property which represents the server's response.

The Last line of the above code updates the relevant portion of the page. We have created the span tag with id details to show the details of the books.

More on readystate

readystate property can have the following values:

Value Description
0 Uninitialized. The object is not initialized with data.
1 Loading. The object is loading its data.
2 Loaded. The object has finished loading its data.
3 Interactive. The user can interact with the object even though it's not fully loaded.
4 Complete. The object is completely initialized.


Using these values we can provide user with feed back. Consider the code below
function pageUpdate()
{
 	if(xmlHttp.readyState == 0)
	{
document.getElementById('details').innerHTML = "Sending Request...";
	}
	if(xmlHttp.readyState == 1)
	{
 document.getElementById(' details ').innerHTML = "Loading Response...";
	}
	if(xmlHttp.readyState == 2)
	{
     document.getElementById(' details ').innerHTML = "Response   Loaded...";
	}
	if(xmlHttp.readyState == 3)
	{
	 document.getElementById(' details ').innerHTML = "Response Ready...";
	}
	if(xmlHttp.readyState == 4)
	{
	document.getElementById(' details ').innerHTML = reponse;
               }
}
Putting it all together
<script language="javascript">
function showbooks()
{

		var cat= document.getElementById("category").value;

     var url = "getbooks.php?cat=" + escape(cat);

	         xmlHttp.open("GET", url, true);
		
	
                  xmlHttp.onreadystatechange = updatePage;

	

   		xmlHttp.send(null);
	
                  

}
function pageUpdate()
{
 	if(xmlHttp.readyState == 0)
	{
document.getElementById('details').innerHTML = "Sending Request...";
	}
	if(xmlHttp.readyState == 1)
	{
 document.getElementById(' details ').innerHTML = "Loading Response...";
	}
	if(xmlHttp.readyState == 2)
	{
     document.getElementById(' details ').innerHTML = "Response   Loaded...";
	}
	if(xmlHttp.readyState == 3)
	{
	 document.getElementById(' details ').innerHTML = "Response Ready...";
	}
	if(xmlHttp.readyState == 4)
	{
	document.getElementById(' details ').innerHTML = reponse;
               }
}

<script>
Server Side Code
PHP Developer
Print("<table bordercolor='#89A0D6' border='1' cellpadding='0' 
cellspacing='0 >");
   Print(" <tr>");
      Print("<td bgcolor='#89A0D6'  width='20%'> </td>");
      Print("<td  bgcolor='#89A0D6' width='20%'><b>Title</b></td>");
   Print("	  <td bgcolor='#89A0D6'
width='20%'><b>Author</b></td>");
      Print(" <td bgcolor='#89A0D6' 
width='20%'><b>Price</b></td>");
      Print("<td bgcolor='#89A0D6' width='20%'><b>Add to 
Cart</b></td>");
   Print(" </tr>");
     
        	
        		
           $link=mysql_connect("localhost");
           mysql_select_db("ajaxexample");
           $query="select * from books where category=cat;
           $result=mysql_query($query);
           while($row=mysql_fetch_array($result))
           {
                      $title=$row ["title"];
                      $author=$rowcart["author"];
                      $price=$row ["price"];
                      $image=$row ["image"];
										
                      print("<tr>"");
                      print("<td bordercolor='#FFFFFF'
width='20%'><img src='images/$image' height='50' width='50' /></td>");
                      print("<td bordercolor='#FFFFFF' 
width='20%'>$title</td>");
                      print("<td bordercolor='#FFFFFF'
width='20%'>$author</td>");
                      print("<td bordercolor='#FFFFFF' 
width='20%'>$price</td>");
          				
                      print("<td bordercolor='#FFFFFF' 
width='20%'><a href=addtocart.php?bid=$bid><img src='images/cart.jpg'
height='30' width='30' /></a></td>");
                      print("</tr>");
           }
        	
        	
           }
        	
   print("  </table>");
Positives of using AJAX
  • High Interactivity
    AJAX application are more interactive then conventional web applications
  • High Usability
    Updating only relevant portion on each user request will improve the usability of your application.
  • High Speed
    AJAX applications are much faster then conventional web application.
Besides these AJAX has many other benefits.

Drawbacks of using AJAX
  • If JavaScript is not activated on the client's PC AJAX won't work
  • Writing and managing complex JavaScript and XML.
  • Initial page load is slow.
  • The data loaded is dynamic so it can't be used for searching by search engines.
  • An interesting problem occurs when the user of the AJAX enabled application clicks the back button Ð nothing happens!
Lastly, XmlHttpRequest can be difficult to integrate into a browser. If a user follows Microsoft's security instructions, they will not be able to use AJAX applications in Internet Explorer (at least, not without accepting a prompt each time). For that reason — and to enable the back-button — developers sometimes have to go with an IFrames-based solution. The early AJAX solutions did this, as does Google Maps. While IE7 is expected to handle XHR correctly, as a javascript function and not an ActiveX object, you should expect to spend a fair amount of time testing and tweaking browser compatibility.

Conclusion
AJAX is a great tool for web applications that require a lot of interactivity and user input. Looking at both the strengths and weaknesses of AJAX, however, it becomes clear that there is a trade off Ð the higher the usability for an application's end users, the greater the complexity for an application's developers. For every project, developers should weigh AJAX' pros and cons and consider that trade-off for themselves.