Build a Reusable AJAX Class

Build a Reusable AJAX Class

Building a reusable AJAX class can help you eliminate some of the headaches when you’re starting out:

Open a new file called connection.js and type the following lines in to start building your class:

function AjaxConnection() {   this.setOptions=setOptions;   this.getOptions=getOptions;   this.connect=connect;   this.uri="ajax_service.php";} function setOptions(opt){   for(i=0;i

The first line declares your new class. To use this class in your pages, include the connection.js file in your header and call it:

    var connection = new AjaxConnection(); 

The next two lines declare the public functions getOptions and setOptions. You can access these functions through the connection object you initialized above. Access them like this:

    connection.getOptions();    connection.setOptions(new Array("action=getList","user=me")); 

Now, call setOptions with an array, because you want to sort through any options and create the correct POST list for later.

The next two lines declaring the connect() function and the URI that it will use:

    this.connect=connect;    this.uri="/services/ajax_service.php"; 

To create the connect() function, type the following lines at the end of your class:

        function connect(return_func)        {            with(this)            {                x=init_object();      "POST", uri,true);                x.onreadystatechange = function() {                        if (x.readyState != 4)                                return;                        eval(return_func + '(x.responseText)');                        delete x;                }                x.setRequestHeader('Content-Type',                    'application/x-www-form-urlencoded');                x.send(options);            }        }

You'll notice that the connect function takes input to initialize it (return_func). This input will be the name of a callback function for the data to be sent to when it's retrieved from the page.

The next main line calls a private function:


This function initializes the XMLHttpRequest object and returns it to the x variable.

Next, you have to set up your connection to the ajax_services.php file:"POST", uri,true);    x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 

Next, you need to create a state change function that will act on different states of the connection and return the data to your callback function:

    x.onreadystatechange = function() {    if (x.readyState != 4)    return;    eval(return_func + '(x.responseText)');    delete x;    } 

Basically, you're ignoring all the states except 4, because you know that's the state you get when you've gotten a succesful connection. Once you know you've got a readyState == 4, you can return the data to your callback function and delete the XMLHttpRequest object because you don't need it any more.

This class still isn't complete. It needs a private function to initialize the XMLHttpRequest object to send the request with. To add this function, type the following lines into your file:

function init_object() {        var x;        try {                x=new ActiveXObject("Msxml2.XMLHTTP");        } catch (e) {                try {                        x=new ActiveXObject("Microsoft.XMLHTTP");                } catch (oc) {                        x=null;                }        }        if(!x && typeof XMLHttpRequest != "undefined")                x = new XMLHttpRequest();        if (x)                return x;}

Here, you attempt a few different types of object initializations until you finally find one that works for the browser accessing the object. If you look in the connect function, you'll see the initial x object being initialized by calling init_object() which then returns the first successful XMLHttpRequest object it finds.

You still need to create an ajax_services.php file to retrieve the data from. Create the following ajax_services.php file in the same directory as the page accessing it:

Now, you can create the following in a page to test out your new AJAX class:

connection = new AjaxConnection();opts = new Array("firstname=Joe","lastname=User");connection.setOptions(opts);connection.connect("callBack");function callBack(content) {        alert(content);}

Shortly after loading this page, you should get an alert window containing the message Hello Joe User. This is the content coming back from the Web connection you created.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist