gregdoolittle.com

chronicling the fate of a warrior: Ajax the Great

January 19th, 2007

I bought my text book for my Ajax class (I also bought my book for my Database class, but hey, that’s just not exciting!). I hope to document my experience learning Ajax in this blog. The class doesn’t begin until March 21st, but I’m planning to work through as much of the material as I can before then, so I can apply it to my new job.

Just finished the Chapter 1 tutorial. Some points to remember:

•The main goal of using Ajax: to reduce the need for data transfer within a web page, therefore increasing your site’s ability to react quickly to user activity.
•Ajax should be able to function in every JavaScript-enabled browser.
•The Ajax request object has not been standardized among browsers. In Firefox/Safari/Opera/IE7, you use the XMLHttpRequest object. In IE6 you use ActiveXObject(”Msxm12.XMLHTTP”). And in IE5 and earlier you use ActiveXObject(”Microsoft.XMLHTTP”). You should account for this every time you create an Ajax request object.
•An Ajax-script is usually called by an event handler (onClick, onChange, onMouseOver, onBlur, onKeyUp, etc.).
•The browser keeps track of a request’s “ready state”. When the ready state is equal to “4″, it means the request is done retrieving information. The DOM aspect of the script must wait until this ready state is achieved. Otherwise, the script will finish running before the information is available.

Every Ajax script will require an object to hold the request, followed a bit of browser-sniffing to apply the appropriate type of Ajax object:

var request = null;
 try {
  request = new XMLHttpRequest();
 } catch (trymicrosoft) {
  try {
   request = new ActiveXObject("Msxml12.XMLHTTP");
   } catch (othermicrosoft) {
    try {
     request = new ActiveXObject("Microsoft.XMLHTTP");
     } catch (failed) {
      request = null;
     }
   }
 }
 if (request == null)
  alert("Error creating request object!");

Usually followed by these lines of code:

var url = "example.php";
request.open("GET", url, true); // true means this is an asynchronous request
request.onreadystatechange = updatePage; /* updatePage() is a function that will use DOM
methods to alter the page hierarchy */
request.send(null); // the request.

If you’d like to see my first, and very dorky, Ajax “application”, you can get to it here (update 01/21/07: just added a random parameter to the URL of the request object, which fixes a bug in IE and Opera). In this case the amount of data transfer saved by using Ajax (as opposed to requesting an entire HTML file) is so minimal that it hardly justifies the time spent constructing the Ajax script. But imagine that this feature was part of a page that did have a lot of elements (say, a couple of 8MB image objects). In that case, using Ajax for such a minute section of a page would be worthwhile, because it would avoid reloading the large amounts of data sitting around elsewhere on the page.

Powered by WordPress