advertisement
Premier Club Log In/Registration
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   SKILLBUILDING  |   TIP BANK  |   SOURCEBANK  |   FORUMS  |   NEWSLETTERS
Browse DevX
Partners & Affiliates
advertisement
advertisement
Tip of the Day
Average Rating: 1/5 | Rate this item | 3 users have rated this item.
Expertise: Advanced
Language: Java
March 29, 2006
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<opt.length;i++)  
   {
      this.options += "&"+opt[i];
   }
}
function getOptions()
{
   return this.options;
}
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();
                x.open("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:


    x=init_object(); 
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:


    x.open("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:


<?php
echo "Hello ".$_REQUEST["firstname"]." ".$_REQUEST["lastname"];
?>
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.

Matthew Brichacek
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible. Submit your tip here.
Please rate this item (5=best)
 1  2  3  4  5
advertisement
advertisement
Advertising Info  |   Member Services  |   Permissions  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs