How to use Sarissa Ajax Library

I’ll spell it out for you. Or even better, I’ll just give you the code! This is the first part of a tutorial covering the Front-end browser part of Ajax’ing and the Back-end part of sending data with PHP. The second part can be found here.

I am only going to explain the minimums for accomplising this goal. A bigginers lesson if you want. I won’t cover more complex options as I don’t need to use them myself, yet.

The Sarissa Ajax library is my choice for Ajax’ing for a few reasons:

  • It’s small (11.8kb!)
  • Cross browser compatible and
  • Escapes the information received nicely

My tutorial will only cover XML request with Sarissa.
What you need to get started:

  • A web development server (consider Wamp if you’re using Windows)
  • Latest versions of your browser (IE 7 not required, the latest IE 6 is fine)
  • The Sarissa Library
  • Cross Browser X Library javascript functions – Optional, for DOM functions you may use.

At this point I should mention that if you’re reading this article, I assume you’re serious about writing your powerful Web 2.0 applications. If you don’t know your DOM or Javascript language very well, I suggest you take a look at this Sitepoint book. The sample chapters are free and they will help you out quite a bit. Purchase the book if you like it.

So, let’s view the major function for our javascript code, assuming you’ve linked to sarissa.js in your document:

//  getUrl
//  Will initate the http request for data.
function getUrl(url,fn) {
  if (url && fn) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", url, true);
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4) {
        fn(xmlhttp.responseXML);
      }
    };
    xmlhttp.send('');
  } else {
    alert('url or function not specified!');
  }
}
 
//  trim functions
//  will trim whitespace from strings
String.prototype.trim=function(){
  return this.replace(/^\\s*|\\s*$/g,'');
}
String.prototype.ltrim=function(){
  return this.replace(/^\\s*/g,'');
}
String.prototype.rtrim=function(){
  return this.replace(/\\s*$/g,'');
}
 
//  CheckResultIsOk
//  Will check the XML data you've return for <error_code>x</error_code>
//  and returns the error to the user if found.
function checkResultIsOk(xml) {
  if (!xml) {
    //xml data was empty. Result was not ok.
    return false;
  }
  if (xml.getElementsByTagName('error_code')[0].firstChild.data &&
    Math.abs(xml.getElementsByTagName('error_code')[0].firstChild.data.trim()) > 0) {
    //error has been supplied
    alert('Error ' + xml.getElementsByTagName('error_code')[0].firstChild.data + ': ' +
      xml.getElementsByTagName('error')[0].firstChild.data.trim());
    return false;
  } else {
    //no errors!
    return true;
  }
}

Download this code: sarissa_tute_1.js

The functions are very simple.

  • getUrl takes an URL, and a function name before opening a http request. The URL should point to the file on your server, from which XML data would be returned. The function name is just the name of a function you’ve already specified. This function gets called once the XML data has been returned. And you’ve probably guessed I like error checking. The alert reponse can be omitted – it’s just there for our testing purposes.
  • trim functions are a few ingenious pieces of code that will save you years of headaches. As some XML documents are formed, whitespace can occur around the data within the tags. These functions can remove this from your strings.
  • checkResultIsOk will check your XML data that you’ve returned for any specified errors. Of course, this only works if your XML document contains a valid error_code tag with an error number in the data, zero being no error. I started using this method of checking so that I could return errors with my back-end system to the user in a friendly manner. Setting an error tag with a description in your XML will also display that to the user.

Believe it or not, but that’s the hard part over. All you need to do now is create your functions to request your data, and additional callback functions to process the data. Here’s an example of a request function:

//  ajaxGetItems
//  Called from clicking a link or button on your page
function ajaxGetItems() {
  //send the request	
  var filetouse = '_ajax.php?mode=getitems';
  getUrl(filetouse,cbGetItems);
}

Download this code: sarissa_tute_2.js

Easy wasn’t it? Notice you can include GET variables in your request. So if your XML document is a dynamic script (as in part two of this tutorial) you can control some aspects of the script. Also notice that when you specify the function name for getUrl, you don’t wrap it in quotes, and you don’t add () to the end of it, otherwise the function would be executed right there at that point in the code.

So let’s assume this is the XML data that has been returned:

<?xml version="1.0" encoding="iso-8859-1"?>
<xmlresponse>
  <item_count> 4 </item_count>
  <item>
    <id> 15 </id>
    <name> Finger Bun </name>
    <price> $0.80 ea </price>
  </item>
  <item>
    <id> 16 </id>
    <name> Donuts </name>
    <price> $0.50 ea </price>
  </item>
  <item>
    <id> 17 </id>
    <name> Apple Pie </name>
    <price> $1.20 slice </price>
  </item>
  <item>
    <id> 18 </id>
    <name> Double Choc Chip Cup Cakes </name>
    <price> $1.00 ea </price>
  </item>
  <error_code> 0 </error_code>
</xmlresponse>

Download this code: sarissa_tute_1.xml

So in our document we have an item_count tag, 4 items tags with sub tags, and our error_code tag. Let’s see how our callback function would handle this:

//  cbGetItems
//  Called when the data from ajaxGetItems has been retrieved.
function cbGetItems(xml) {
  //check result is ok
  if (checkResultIsOk(xml)) {
    //get the item count
    var item_count = Math.abs(xml.getElementsByTagName('item_count')[0].firstChild.data.trim());
 
    //get the items
    var items = xml.getElementsByTagName('items');
    for (i=0;i<items.length;i++) {
    //send an alert of the data received
      alert (i + "  Data recieved:\\n" +
        "id: " + items[i].getElementsByTagName('id')[0].firstChild.data.trim() + "\\n" +
        "name: " + items[i].getElementsByTagName('name')[0].firstChild.data.trim() + "\\n" +
        "price: " + items[i].getElementsByTagName('price')[0].firstChild.data.trim() + "\\n");
    } //end i for		
  } //end check result
} //end function 

Download this code: sarissa_tute_3.js

The first things the function does is check the data for an error with the checkResultIsOk function. If it passes, we extract the data. The item_count tag isn’t being displayed to the user, I’ve only put it in there to show you how to extract a single tag (that doesn’t have an ID). Next we get all the items tags, iterate through them and display the data in alert popups. You can do whatever you like with the data I’ve used in these alerts.

So there you have half of it! Using Sarissa to retrieve XML data and do something with the data, all with cross browser functionality. Now take part two of the tutorial and learn How to dynamically return XML data using PHP

Technorati: javascript, ajax, xml, tutorial, sarissa


Share this Post:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • StumbleUpon
  • Slashdot
  1. written by Bubbila March 28th, 2008 at 07:13 | #1

    Sweet resource, just what I have been looking for.