Simple AJAX Example

AJAX (Asynchronous Javascript and XML) is a technique for creating dynamic Web pages. AJAX is used to change elements of a Web page without reloading the whole page from the server, thus increasing performance and responsiveness. It was first named in 2005 and now is a relatively mature technology. All major browsers support it, popular sites use it heavily, and many Web development tools and languages build upon it. For more background about AJAX, see this Wikipedia article.

This page demonstrates basic AJAX functionality. The most popular way to use AJAX is via Javascript that is executed by user actions or a timer. The Javascript makes a request to the Web server, and when a response is received, HTML elements on the page are updated with the new information. Since this occurs asynchronously (in other words, is non-blocking), the user can interact with the Web page while AJAX request/response communication is happening, and so perceives that the page is more responsive.

Assume that you're building a Web page that displays a counter. This counter could show the number of messages the user has, time spent on the site, or similar information. You want the counter to get new information from the server without reloading the rest of the page.

Here are a counter and a button that uses AJAX to call a server-side method to update the counter's value:

10

Click on the button to see AJAX in action.

The HTML source for the counter and button:

<p id="counter">10</p>
<input type="button" name="button" value="Update" onClick="ajaxUpdate('counter')">

Clicking the button makes your browser call the Javascript method ajaxUpdate(). This method performs the function calls to get information from the server and update the page's HTML elements. Here's the basic ajaxUpdate() function used in this example:

function ajaxUpdate(id){
 elt = document.getElementById(id);
 var req = getXMLHTTPObject();
 req.open("GET", "/t/counter.php?v="+elt.innerHTML);
 req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
 req.onreadystatechange = function(){
  if (req.readyState == 4 && req.status == 200){
   if (req.responseText){
    elt = document.getElementById(id);
    elt.innerHTML = req.responseText;
   }
  }
 };
 req.send(null);
}

To understand how AJAX works, carefully read each line of this function. It first takes the parameter id and gets the HTML element with this id. Then it calls getXMLHTTPObject() to get a XMLHTTP object. This object is the key piece of AJAX since it makes a request to the Web server and handles the result asynchronously; in other words, without making the browser wait for the reply. The next line tells the object what URL to make the HTTP request to. Here, a short PHP script called counter.php will be called, which simply takes the URL parameter v and returns v+1. The next line sets what type of data will be sent to the URL. The object's onreadystatechange attribute is set to a Javascript function that will be called when the HTTP request gets a response. In this case, the function again gets the page element with the provided id, and sets its innerHTML attribute to whatever the HTTP request returns. Finally, the XMLHTTP object's send() method is called to actually perform the HTTP request.

Different browsers have different ways of obtaining an XMLHTTP object. The getXMLHTTPObject() function is a standard way of getting this object across all popular browsers. Here is the source code for this method:

function getXMLHTTPObject(){
 if (window.XMLHttpRequest) return new XMLHttpRequest();
 try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
 try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
 try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
 try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
 throw new Error("Could not create XMLHttpRequest");
}