Modelworks Software Logo


AJAX

Home

Products

Product
Comparisons


Features

Screen Shots

Downloads

Updates

Free License

Support

Solutions

FAQ

Papers
   AJAX
   JSON

Editors
   Java
   HTML
   Perl
   JSP
   JavaScript
   PHP
   VBScript
   Velocity
   XML


The AJAX term was coined by Garrett. It stands for Asynchronous JavaScript And XML and is somewhat misnamed since XML is not required. One use of AJAX is to let you build web pages that are more like traditional client based applications. For example, with AJAX you can auto complete an input element using data from a server. These applications are called internet applications. You will also hear them referred to as Web 2.0 applications. Another use of AJAX is to eliminate full page reloading when only part of a page needs to be updated with data from a server.

In this tutorial we will show you how you can use AJAX to record and then show the results of a poll, vote, user preference, yes/no choices or ratings submissions in a page. We will also identify some of the issues facing AJAX developers.

To see where we are going, try the following poll. You should see a bar chart showing the current votes.

Do you prefer cats or dogs?
Cats
Dogs

The key technology that makes AJAX work is the XMLHttpRequest JavaScript object. The XMLHttpRequest was first implemented by Microsoft as an ActiveX object in IE 5.0 (March 1999). Then Mozilla added a compatible XMLHttpRequest object for Mozilla 1.0 and Netscape 7 (May 2001). This was followed by Apple's support in Safari 1.2 (February 2004) and Opera's support in version 8.5 (September 2005).

Here is the AJAX sequence diagram that shows how the XMLHttpRequest is used.

AJAX Sequence Diagram

The AJAX process starts with a DOM event. In step 1 you need to obtain a XMLHttpRequest object. This is typically done using a function like the following so that the code will work on different browsers:

function GetXMLHttpRequest() 
{
    var object = null;
    
    if (window.XMLHttpRequest) 
    {
        object = new XMLHttpRequest();
    } 
    else if (window.ActiveXObject) 
    {
        try
        {
            object = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e)
        {
        }
        
        if (object == null)
        {
            try
            {
                object = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e)
            {
            }
        }
    }
    
    if (object == null)
    {
        alert("Your browser does not support AJAX");
    }
    
    return object;
}

After you have the XMLHttpRequest object, you then need to set the 'onreadystatechange' callback function and call the 'open' and 'send' methods using code:

XMLHttpRequestObject.onreadystatechange = ProcessRequest;
XMLHttpRequestObject.open("GET", url, true);
XMLHttpRequestObject.send(data);

Note that the data that you send and receive when using the XMLHttpRequest object can be in any format. It does not need to be XML. We recommend that you look at JSON in place of XML. JSON is a subset of the literal object notation in JavaScript that includes many of the features of XML. If your application is fairly simple you could also use traditional name value pairs.

At the end of step 1 you should provide the user some visual indication that something has changed. In the examples on this page we rename the Vote button to Loading...

In step 2 you will need to have a handler that processes your request on the server. The handler can be a CGI or other server side script such as PHP, ASP, or JSP.

In step 3 you will need to process the response using your ProcessRequest function. It should look something like the following:

function ProcessRequest() 
{
    if (XMLHttpRequestObject.readyState == 4) 
    {
        if (XMLHttpRequestObject.status == 200) 
        {
            var result = Parse();
            if (result)
            {
                // Update HTML based on the result
            }
        } 
        else
        {
            // An error has occurred.
        }
    }
}

Be sure to check ready state and status codes since the handler will be called with different ready states and status codes. In this tutorial we are only interested when the call is complete.

Important: Because the ProcessRequest function is being used as a callback you do not have control over when or if it will be called.

Possible XMLHttpRequestObject.readyState codes are:

0 - uninitialized
1 - loading
2 - loaded
3 - interactive
4 - complete

XMLHttpRequestObject.status codes are just HTTP status codes.

Examples

The AJAX example below lets a user enter a vote and then see the results. To try it choose your color and then press the Vote button.

Choose your favorite color:
Red
Green
Blue

The code to display the choices for choosing your favorite color looks like this:

<div id="colorvotediv">

    <p><b>Choose your favorite color:</b><br>
    <input type=radio barcolor="red" name="colorvote" label="Red" value="red" checked>Red<br>     <input type=radio barcolor="green" name="colorvote" label="Green" value="green">Green<br>     <input type=radio barcolor="blue" name="colorvote" label="Blue" value="blue">Blue<br>
    <input type=button value="Vote" onclick="OnVote('colorvote', '')"></p>
</div>

Parameters are passed to the AJAX enabled OnVote function using custom attributes. The OnVote function locates the vote box by looking for an 'ID' of voteName + 'div' which results in the ID 'colorvotediv' for the div above. Each of the input tags must have the 'name' attribute set to voteName. The 'value' attribute should be a legal JavaScript variable name. The 'barcolor' attribute specifies the color of the resulting bar and the 'label' attributes specifies the bar label.

It is easy to change the vote by just changing the HTML in the div tag. Here is another example that asks for your favorite language.

Choose you favorite language
C/C++
C#
Java
JavaScript
HTML
PHP
ASP

The Code

Besides the utility functions there are two main functions for this example. The OnVote function sets up the AJAX process for a vote. It is triggered when the user clicks on the Vote button. The OnVoteProcess function is the callback that is responsible for processing the data and generating the bar chart. Both functions use a common global array XMLHttpRequestObject to maintain the vote data keyed by the votename.

The OnVote function starts by getting the XMLHttpRequest and then initializing the array element XMLHttpRequestObject[votename]. It then defines the url that will be used to save and get the vote data from the server. Since we are using the 'GET' method we must append the data to the url. In this tutorial we are using a list of variable=value pairs separated by '&'. At the same time we save the bar color and label in the XMLHttpRequestObject[votename] object. Then we open the url, set the request header and call send. At this point the browser waits for a new event.

function OnVote(votename, title)
{
    if (XMLHttpRequestObject == null)
    {
        XMLHttpRequestObject = new Array;
    }
    
    if(XMLHttpRequestObject[votename] != null)
    {
        return;
    }
    
    var requestObject = GetXMLHttpRequest();
    if (requestObject)
    {
        XMLHttpRequestObject[votename] = new Object();
        XMLHttpRequestObject[votename].requestObject = requestObject;
        XMLHttpRequestObject[votename].title = title;
        XMLHttpRequestObject[votename].color = new Array();
        XMLHttpRequestObject[votename].label = new Array();

        requestObject.onreadystatechange = new Function ("OnVoteProcess('" + votename + "')");

        var url = URL + "?" + "votename=" + votename + 
            '&' + "vote=" + (document.cookie.length > 0 ? 'true' : 'false');
        var voteChoices=document.getElementsByName(votename);
        for(var i=0; i < voteChoices.length; i++)
        {
            url += '&' + voteChoices[i].value + '=' + (voteChoices[i].checked ? 1 : 0);
            XMLHttpRequestObject[votename].color[i] = voteChoices[i].getAttribute('barcolor');
            XMLHttpRequestObject[votename].label[i] = voteChoices[i].getAttribute('label');
        }

        requestObject.open("GET", url, true);
        requestObject.setRequestHeader( "Content-Type" , "application/x-www-form-urlencoded; charset=UTF-8" );
        requestObject.send("");
    }
}

The second function is the OnVoteProcess function. It is the callback function that is called by the XMLHttpRequest object. In this case the OnVoteProcess function processes the vote data returned by the server and then builds a bar chart using a custom BarChart JavaScript class. Here is the code:

function OnVoteProcess(votename)
{
    if (XMLHttpRequestObject[votename].requestObject &&
        XMLHttpRequestObject[votename].requestObject.readyState == 4) 
    {
        if (XMLHttpRequestObject[votename].requestObject.status == 200) 
        {
            var result = XMLHttpRequestObject[votename].requestObject.responseText;
            if (result == "busy")
            {
                alert("The server is busy. Try again.");
                XMLHttpRequestObject[votename] = null;
            }
            else
            {
                var variables = result.split('&');
                
                // Create an BarChart instance
                var chart = new BarChart(XMLHttpRequestObject[votename].title, 70, 130, 18, "white");
                
                for (var i = 0; i < variables.length; i++)
                {
                    var variable = variables[i];
                    var item = variable.split('=');
                    chart.addBarData(XMLHttpRequestObject[votename].label[i], 
                        item[1], XMLHttpRequestObject[votename].color[i]);
                }
                
                var name = votename + "div";
                var divContainer = document.getElementById(name);
                if (divContainer)
                {
                    // Generate HTML for the BarChart using the DOM
                    chart.replace(divContainer);
                }
                
                XMLHttpRequestObject[votename] = null;
            }
        } 
    }
}

The remaining piece of the code is the server side code that records the vote. For this tutorial, we used a PHP script, but we could just as easily used any server side code, including C/C++, to record the vote.

Security

The XMLHttpRequest object uses the same domain security policies as JavaScript. This means that the domain of the URL used for the XMLHttpRequest object must be the same as the as the server providing the page in order to avoid security warnings or failures (depending upon the browser).

This means that client side scripts cannot conveniently use the XMLHttpRequest object to directly obtain information from other domains without getting a security warning. One workaround would be to use server side code installed on your server to specifically obtain the data from other servers.

Uses of AJAX

AJAX has many potential uses. Here are a few of them:

  • Updating page information
  • Real-time data validation
  • Obtaining data for a control
  • Responding to server events
  • Pushing data to the client
  • Real-time interaction
  • Real-time monitoring
  • Auto completion

Don't forget DHTML and JavaScript

DHTML and JavaScript can offer many useful data and visual manipulation without needing to communicate with a server. See Rico for a JavaScript library of interesting effects. Rico also includes an open AJAX library.

Integration with Other Technologies

Keep in mind that you don't need to use AJAX for all communication with your server. For example, if you just want to log data to your server then you can use the image tag like this:

if (document.images)
{
    var image = new Image(1,1); 
    image.src = "http://someplace.com/cgi-bin/mylog.cgi?" + data; 
}

This is the technique that Google(tm) Analytics and others are using to record web site statistics. Even though this technique is often derisively referred to as a web bug, we recommend using this technique for internet applications so you can have some insight into what your users are doing. You could even combine AJAX and the image tag technique to provide real-time monitoring of your site.

The Technology

As with all technology, there are issues that you will need to deal with when using AJAX. Some of these issues include:

  • AJAX requires both client side and server side code. This means that you have more technology to master. It also means that you will have to rely on client side technology which you do not control. At a minimum it means knowing DHTML, JavaScript and at least one server side technology.


  • Debugging will be more difficult since you will need to debug both client and server code in a distributed environment. Be sure to set up your local development server to be as close to your live server as you can. For example, if you are using PHP do not use PHP 5.0 on your local server if your live server is using PHP 4.06.


  • All client side code is viewable including all JavaScript used on the client. So if you have any secrets be sure to put them on the server side. You may also want to minimize and obfuscate your JavaScript.


  • You may need to consider using an AJAX enabled framework as your application gets more complex.


  • Content only shown by AJAX cannot be indexed by search engines. And even if it were indexed it would difficult to construct an URL that a search engine could directly reference.


  • There are some — often subtle — differences between browsers and different versions JavaScript. This means that you will need to test on multiple platforms and gracefully degrade as needed.

Conclusion

In this article we have shown you how you can use AJAX to record and then show the results of a poll or vote. And we have identified some of the issues that AJAX developers will face.

Please rate this article
5  Best    

 
Copyright 1996-2008  |  About Us  |  Contact Us  |  Privacy Statement  |