Quick 'n Dirty Ajax Class

This article discusses a tiny XMLHttpRequest object that can be used to make HTTP requests from javascript. There's a bazillion tutorials out there showing you how to do just this, and there's about half as many complete frameworks. But if you like doing your own javascript this might give you some inspiration.

Request = function(url, callBack)
{
    this.url        = url;
    this.callBack   = callBack;
    this.request    = null;
    this.parameters = "";
   
    // For use when 'this' points to the caller
    var me = this;
   
    this.send = function()
    {
        me.request = (window.XMLHttpRequest)? new XMLHttpRequest(): new ActiveXObject("MSXML2.XMLHTTP");
        me.request.onreadystatechange = this.handleCallBack;
        me.request.open('POST', me.url, true);        
        me.request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        me.request.setRequestHeader("Content-length", me.parameters.length);
        me.request.setRequestHeader("Connection", "close");
        me.request.send(me.parameters);
    }
   
    // Adds a parameter
    this.add = function(name, value)
    {
        if (!me.parameters.isEmpty()) me.parameters += "&";
        me.parameters += encodeURIComponent(name)+"="+encodeURIComponent(value);
    }

    // Returns a HTTP status or null if the request isn't ready.
    this.getState = function()
    {
        if (me.request == null) return null;
        if (me.request.readyState != 4) return null;
        return me.request.status;
    }
   
    // Returns the response.
    this.getResponse = function()
    {
        if (me.request == null) return null;
        if (me.request.getResponseHeader('Content-Type').indexOf('xml') != -1)
            return me.request.responseXML.documentElement;
        else
            return me.request.responseText;
    }
   
    // Calls the user specified callback function.
    this.handleCallBack = function()
    {
        if (me.request.readyState != 4) return;
        me.callBack();
    }
}

To use this class you create a new Request class with two parameters:

After creating the object you add any amount of parameters and call the send() method. The request is sent and when the server returns a response the callback is called. Because the callback is called from the Request object (instead of directly from the XMLHttpRequest object) the callback function can access the Request object through the this keyword.

Here's an example:

ExampleClass = function()
{
    var me = this;

    this.save = function()
    {    
        var request = new Request('save.php', me.saveDone);
        request.add('data', 1234);
        request.add('text', 'Text123!');
        request.send();
    }

    this.saveDone = function()
    {
        if (this.getState() != 200) alert("Failed to save data!");    
        var theResponse = this.getResponse();
        //Do stuff with the response
    }
}

And that's why it's quick.

But why is it dirty

Two main reasons:

Nonetheless, I'll be playing around with this for a while :)

Dec 27th, 2008

Comments

No comments yet! Feel free to post some using the form below.

Post your comments here

If you wish to add code to your comment you can use code tags, like this: <code class="php">yourCodeHere</code>.
Quite a large number of languages are supported, although I can't guarantee it'll be pretty. Inside the code tags you can use any characters except for the string "</code>".