rob cherny.com

About

My name is Rob Cherny and I'm a professional Web Developer with 16 years of experience creating Web sites and Web-based applications. This site is where I write about my work, and random other things...

Learn More

Loading...

Close Tab

Web Development

JavaScript Ajax Object Script

So there's tons of code out there here and there, so does the world really need another Ajax script? Not really, but I figured someone might like it. I wrote this last year, but it still works just fine and has some advantages a lot of the more common libraries don't have -- one of which is size.

When you can't use a large library like some offer, you might want something smaller. Additionally, with this script I was hoping to expose some of the original strengths of the XMLHTTPRequest object which so many of these funky libraries don't even consider.

At this point, you might want to just jump to the usage section while I ramble on.

Just as an aside, I'm featuring some Ajax goodness on this site, with the "About" "Learn More" tab above. However, I'm not using my Ajax Object script. I already optioned the usage of the excellent jQuery library which includes an Ajax module, and sometimes decisions like that need to be made. There's other features it has that I wanted, so I used it's built in support as it worked for what I needed. What's best for a given project depends on what else you're trying to do and what is available. But that's also another article. Don't double up, your users will thank you in bytes.

The Ajax Object Script Direction

So when I researched the XMLHTTPRequest object to create my Ajax script, I basically decided that what you really needed to be able to do was to place a request and then do something "onload", right? The hardest part to understand of implementing the actual XMLHTTPRequest object in my opinion is getting your head around the notion of "readyState" and being able to take some action as a result of the successful transaction. I wanted to set it up so that all that matters is it's easy to tell if it successfully loaded or not. To do this, I've exposed a specific onLoad handler.

Additionally, if you're creating a custom object wrapper around XMLHTTPRequest I also felt it a little inconvenient that so many properties such as statusText and methods like getAllResponseHeaders() might end up burried a level deeper than the object you might be creating. So I made sure they were pulled up a layer. Also of course, as is common with most scripts which add basic Ajax support these days, is an easy way to add content pulled down into a specific location on the page, so I added a way to place content into a specific DIV element, by #ID. Looking at the code it should be obvious how to add more robust support for handling other processing.

Finally, debugging scripts with Ajax transactions behind the scenes is a pain. So I added a debugging mode which features rudimentary alert()s at each stage to show what's going on. At some point I'd like to add more robust logging to a console or similar support.

In the meantime, you should try the excellent Firebug Mozilla Firefox extension if you want help debugging your Ajax scripts. It features a console which can log all requests and responses. Highly recommended. The debugging here is fairly rudimentary.

Usage of the Ajax Object Script

Simply include the core Ajax Object script in your document, then create a new "AO" object.

  1. var x = new AO("demo.html","");

The AO() constructor is as follows:

object AO(string url, string query)

  1. string url: the URL to be called
  2. string query: the query to be appended to the URL for either a GET or a POST operation. Might be an empty string.

You're then going to setup the onLoad handler, and determine what it is you want to do when the transaction is completed. This might be grab a chunk of HTML, XML to be parsed, or simply provide some user feedback.

  1. var x = new AO("demo.html","");
  2.     x.onload = fuction() {
  3.       // insert code here ...
  4.     }

One of the other things which struck me about so many Ajax scripts out there was the lack of error handling. You might not be able to create the object, the connection might time out, or it's even possible you might get a 404 returned.

To enable debugging, simply set the property to true:

  1. var x = new AO("demo.html","");
  2.     x.debug = true;
  3.     x.onload = fuction() {
  4.        // insert code here ...
  5.     }

I set the script up so that it is possibly to check for error conditions by returning the status, statusText, and all the HTTP Headers so you can run the full gammut of tests on the transaction. This allows for some great possibilities with this script, as all the built in functionality of the XMLHTTPRequest object is available.

Some of the built in methods and properties are a bit combersome, so I've recast them as others that I felt were easier to remember:

  1. XMLHTTPRequest.responseText = AO.txt
  2. XMLHTTPRequest.responseXML = AO.xml
  3. XMLHTTPRequest.getAllResponseHeaders() = AO.headers
  4. XMLHTTPRequest.getResponseHeader = AO.getHeader()

I wanted to make it easier to use, but keep the strengths.

In order to actually execute the transaction, all you do is call either .get() or .post().

  1. var x = new AO("demo.html","");
  2.     x.onload = fuction() {
  3.       // insert code here ...
  4.     }
  5.     x.get();

Finally, just to demonstrate how easy it is to extend, I've added a utility function which can set an object's innerHTML to the responseText, so you can push HTML returned into an element using AO.putHere(#id):

  1. var x = new AO("demo.html","");
  2.     x.onload = function() {
  3.         if (x.init && x.status == "200")
  4.             x.putHere("data");
  5.             // put the .responseText into #data
  6.     }
  7.     x.get();

Demos

I've set up a demo page which demonstrates the script in action in a couple scenarios, including a 404 condition and the debugging enabled. Finally, a simple successful AO.putHere() as mentioned above is included. Enjoy. I'll post any updates here when and if they happen.

Download the Ajax Object JavaScript.

Update #1: Just a note, there's an update coming...

Apr 30, 02:58 AM in Web Development (filed under Ajax, JavaScript)

commenting closed for this article

In This Section