5 easy steps to AJAX

No Gravatar

In talking with other developers, I’ve found many to be confused by AJAX, and what it is, even though it’s quite a simple concept. The name is shorthand for Asynchronous JavaScript + XML. (originally defined by Jess James Garrett here.) It really represents an entire group of technologies in it’s most complex form, but it really doesn’t have to be that complex.

Essentially, the most important component is the Asynchronous part. That’s handled by the XmlHttpRequest object. In general, HTTP is a request-response protocol, meaning that a browser (on behalf of a user clicking on or typing in a link) makes a request to a web server which then creates a response that it sends back to the browser, and the browser then renders that (typically marked up text) back to the user in a visual way. However, if you’ve only got to update one small part of a page, say 500 bytes of a 100 KB page, it’s wasteful to retrieve the other 99.5 KB that’s going to remain the same. That’s where AJAX comes in. What you can do with AJAX is a request-response for only the 500 bytes, then use the browsers’ DOM model to dynamically insert the response back into the page, and the 99.5 KB never changes! Obviously, updates like this are a small subset of what AJAX can do, but turns out to be a large majority of what people use it for.

Let’s see an example in 5 easy steps:

1) Create the AJAX object for the browser and instantiate it:

function getAJAXObject() {
    var aj;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        aj = new ActiveXObject("Microsoft.XMLHTTP");
        aj = new XMLHttpRequest();
    return aj;

var ajax = getAJAXObject();

2) Create the function to send the request to the server:

function sendRequest(name) {
    ajax.open('get', 'getPerson.do?name'+name);
    ajax.onreadystatechange = receiveResponse;

3) Create the function to receive/process the response from the server:

function receiveResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
        var update = new Array();

        if(response.indexOf('|' != -1)) {
            update = response.split('|');
            document.getElementById(update[0]).innerHTML = update[1];

4) Create some back-end server code to accept the request and send the response:

String name = request.getParameter("name");
out.println("username|" + name);

5) Create the link to call the requesting function and the placeholder for the response:

<div id="username">

<a href="sendRequest('abc')">

That’s really all there is to it. Now, you can see how quick and easy it is to roll your own AJAX functionality in an application. There are some great frameworks out there for perform ajax functionality that are heavily used in the java community. If you’d like to use one of those, here are a few to get you started:
Google Web Toolkit

Be Sociable, Share!

Leave a Reply
