Basic AJAX

Just a quick rundown of how to make AJAX work.

I’ve used it a little bit, and keep forgetting a few of the details. So I’m putting this together as much for a quick reference for myself as a tutorial for others.

All AJAX is done inside of Javascript, I’m going to skip the explanation of where that code belongs in your web page and get right to the actual function calls for it. Like all other Javascript, the AJAX functions aren’t concerned where they are in the page so long as they are called in the right sequence.

First you start by creating the AJAX request object. This is done with the XMLHttpRequest() object in Mozilla, Opera, and Safari; and the ActiveXObject() object in Internet Explorer. There are two possibility object types you can request depending on the version of Internet Explorer; Msxml2.XMLHTTP or Microsoft.XMLHTTP. One big nested try/catch block takes care of all of this:

try
{//Mozilla, Opera, and Safari
    AJAXObj = new XMLHttpRequest();
}
catch (err)
{//Internet Explorer
    try
    {
        AJAXObj = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (err)
    {
        try
        {
            AJAXObj = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (err)
        {
            alert("Your browser does not support AJAX!");
        }
    }
}

Now you can use that object to send and receive data from a web server. There are two ways the request can be made asynchronously and synchronously. In the asynchronous mode the request is sent and a call back function is used when the response is received. In synchronous mode the request function won’t return until the response is received.

For asynchronous mode you need to set the callback function in the AJAX object. This is done with the onreadystatechange property. Nothing fancy, just:

AJAXObj.onreadystatechange = function;

So now the function function() will be called in response to AJAX request responses. The callback function will not be passed any values, all the information it needs will be stored in the AJAX object variable.

The callback function will be called several times during an AJAX request. There are a number of state changes that occur that you can react to. The current state of the AJAX request can be found in the readyState property of the AJAX object. It can have any of the following values:

  0 = Uninitialized, no request is being processed
  1 = Open, the request has not yet been passed to the server
  2 = Sent, the request has been sent to the server
  3 = Receiving, the server response is being received
  4 = Loaded, the server response has been completely received

The callback function will need to check that property to determine what actions can be taken. Generally speaking, you’ll want to be sure its a 0 or 4 before sending a request; and a 4 before attempting to make use of the response.

In synchronous mode you can skip all of that, and assume that when the function to place the request returns the server response is completely loaded.

To place the request use the open() method. It can take 5 parameters the HTTP method to use, the URL to send the request to, a toggle for asynchronous mode, a user name to submit the request with, and a password. The last three values are optional, the default is asynchronous mode with no user name or password. So the function will look something like this:

AJAXObj.open("GET", "HTTP://www.webserver.com/", true);

This would setup an HTTP GET request to the www.webserver.com server in asynchronous mode. Setting the third value to false would use synchronous mode. You can request specific web pages or pass GET values in the URL as well.

To actually send the request you need to call the send() method. It takes a single parameter which is additional information to send along with the request. For GET requests you can ignore that and set the parameter to null, for POST requests you can supply a string or an array that includes the data.

Once the server response is received you can retrieve the entire response in the property responseText.

Now to wrap it all up in an example:

<script type="text/javascript">
var AJAXObj;

function AJAXSetup()
{
    try
    {//Mozilla, Opera, and Safari
        AJAXObj = new XMLHttpRequest();
    }
    catch (err)
    {//Internet Explorer
        try
        {
            AJAXObj = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (err)
        {
            try
            {
                AJAXObj = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (err)
            {
                alert("Your browser does not support AJAX!");
            }
        }
    }
}

function AJAXSendRequest()
{
    AJAXObj.onreadystatechange= AJAXReceive;
    AJAXObj.open("GET", "HTTP://www.someserver.com/page.php?GetVar=Value", true);
    AJAXOBJ.send(null);
}

function AJAXReceive()
{
    if (AJAXObj.readyState == 4)
    {
        alert(AJAXObj.responseText);
    }
}
</script>

In this example you’d call the function AJAXSetup() a single time, probably in an on page load event. You’d then call AJAXSendRequest() whenever you wanted to retrieve data from the server. AJAXReceive() would be called when the server response is received.

The responseText property will contain anything the server sense back, headers and all. You’ll want to be sure that your Javascript is able to handle what is being received.

Thats pretty much all there is to getting AJAX going. There are a number of details and options I’ve left out, but to do a simple server query this is all it would take.

2 Responses to “Basic AJAX”

  1. 1
    Tan Says:

    i get this error when i use GET with an external site how do i solve this

    “uncaught exception: Permission denied to call method XMLHttpRequest.open”

    thank you,
    t

  2. 2
    Exile Says:

    Could be two things, depends on your browser.

    Firefox is very strict about AJAX requests, it will only allow requests to the same domain that your page is from.

    You can correct that by adding this line:

    netscape.security.PrivilegeManager.enablePrivilege(”UniversalBrowserRead”);

    To the beginning of the function that creates the AJAX object as well as the function that calls the open method. It will override the security setting.

    If you are dealing with Internet Explorer you’re a bit more limited on options. The only thing I know of that you can do would be to lower the security settings.

    You may want to put all of the pages in the same domain to make sure the AJAX requests and responses are working, before digging into these sort of security problems.

Leave a Reply

© 2007 Mindlence