Saturday, August 12, 2006

AJAX basics

The wirdz site used AJAX to provide much of the functionality and ease of use. This has been taken furthest so far with the Wordnet 2.1 based English Dictionary plus and Roget's Thesaurus.

When this blog started, some technical material of AJAX was promised. So here's a basic intro to start with.

The key to AJAX is that it allows interaction and updated content to be obtained from the back end web/application server without needing a full page refresh. This is what allows the update as you type feature of the itanda dictionary engine to work. It is also the approach behind rich feature applications such as google's online spreadsheet which has been launched in beta status.

The orchestration of the AJAX interaction takes place between javascript running in the browser and whatever active page technology is being used at the back end - this can be PHP, ASP, Java servlets/server pages, Ruby on Rails ... your choice.


The first step on the client/browser side is to create a HTTP request object. Here's the code used on itanda. You'll find variants of this elsewhere on the web. This works with most browsers.
var objReq;

function initialize() {
  try {
    objReq = new ActiveXObject("Msxml2.XMLHTTP");
  }
  catch(e) {
    try {
      objReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e2) {
      objReq = null;
    }
  }
  if (!objReq && typeof XMLHttpRequest!="undefined") {
    objReq = new XMLHttpRequest();
  }
}


Interaction takes place in two stages (a) sending a request and (b) processing the return. Here's some sample script:

/* Send request */
if (objReq != null) {
  objReq.onreadystatechange = processReturn;
  strRequest = "http://www.itanda.com/demo/ajaxDemo1.php"
  objReq.open("GET", strRequest, true);
  objReq.send(null);
}

/* Process return */
function processReturn() {
  if (objReq.readyState == 4) {
    if (objReq.status == 200) {
      if (objReq.responseText == "") {
        response.write(objReq.responseText);
      }
    }
  }
}  

In practice the original request will include some parameters and the return processing will be just a tad more sophisticated.

To complete the picture, here's the classic example played out at the back end in PHP:
<?
echo "Greetings earthlings - we now call the shots" .
     " - forget bringing your leader" .
     " - he's got nothing worth saying!";
?>


And that's it folks ...


0 Comments:

Post a Comment

<< Home