AJAX, an object oriented XML parser

Sunday, September 14th, 2008 | AJAX, JavaScript

A lot of XML parsers that are used in AJAX scripts use a global variable to store the output. This works fine untill you want to want to do multiple requests at the same time. And that exactly should be one of the advantages of AJAX, the ‘a’ of Asynchronous.

So, what’s going wrong when you use a traditional parser? Let’s say you fire a request that takes two seconds to get the data you need. Now, within these 2 seconds you want to fire a new request. But the problem now is that for this request you need the same global variable as you used for the first request and the returned data of the first request will be be overwritten by the data of the second one. A solution would be to make a new global varainble for each request, but I don’t think that is quite a good and flexible solution. The best solution (in my opinion) is to make the parser object oriented. Now every request will get its own object and doesn’t interfere anymore with the other ones.

In this article I’ll give you the code and some explanation for this XML parser. I won’t give a full explanation of how object oriented programming works. You got to find it out yourself :-)

The code

The code itself is a little bit too much to display on this page, so you can download it. In the next paragraphs I’ll exaplain the most important parts.

Initilization

In line 9 to 16 a number of variables are declared which we will use later. After this declaration the init() function is called. This function is called every time a new object is created. You could use this to display a loading image or something like that. At the end of all, the _closeLoading is called where you can kill the loading image.

Settings

After the initialization there are a couple of functions which can be used to change the settings for the object. A short impression:

  • setResponseAsText(): default you will receive the data as XML. Calling this function will return the data as raw text.
  • setDisabledASync(): This function will disable the asynchronous behaviour of the requests. By calling this function all request are handeld after each other.
  • setFunction(): in setFunction() function you can mention all the functions (in comma separated format) that should be called when the data is ready.
  • setURL(url): define the URL of the server side script
  • addParam(param, value): in this function you can define which parameters should be added to the URL of the server side script. Call this function for each paramter.

So this is what it look like to create a new request (getResults is a fictive function):

function getResults(query) {
    var xmlhttp = new HTTPDataConnection();
    xmlhttp.setURL("results.php");
    xmlhttp.addParam("query", query.value);
    xmlhttp.addParam("maxResults", 50);
    xmlhttp.setFunction(processData);
    xmlhttp.requestData();
}

The request

The most important function is requestData(). In this function the actual XmlHTTPRequest is done. handleData() will process the obtained data.

Data processing

The handleData() function gets the data after the request is finished (readystate == 4). The received (XML) data is stored in the this.receive variabele.

Here’s a little example of an XML document:

		<!--[CDATA[Seth Godin]]-->
		<!--[CDATA[9789022994702]]-->
<!--[CDATA[Portfolio]]-->
 
		<!--[CDATA[Malcolm Gladwell]]-->
		<!--[CDATA[9781586217457]]-->
<!--[CDATA[Hachette Audio]]-->

After getting the data all the function from the setFunction() function are being called.At the end _closeLoading() is kicked wheere you can finalize your request a let your loading images disappear.

Displaying the data

If you to show the data on the screen you can do this in one of the functions that is been called after the request. In the example below this function is called processInput(). The comments are clear enough I think :-)

function processInput(xmlhttp) {
	// get data as an array, with XML element 'object' as root
	var dataArray = xmlhttp.getDataAsArray("object");
 
	// get number of results from XML element 'count'.
	var count = xmlhttp.getDataValue("count");
 
	if(count != 0) {
		if(count &gt; 25) {
			output ="
 
<em>There are more than 25 results. Please refine your search query.</em>
 
";
		}
		else {
			output ="
 
<em>There are " + count + " results found</em>
 
";
		}
 
		for(var object in dataArray) {
			if(typeof(dataArray[object]) == "object") {
				var title = dataArray[object]["title"];
				var author = dataArray[object]["author"];
				var ean = dataArray[object]["ean"];
				var publisher = dataArray[object]["publisher"];
				output += "
 
";
				output += "<strong>" + title + "</strong>, " + author + "";
				output += "EAN: " + ean + "";
				output += "Published by: " + publisher;
				output += "
 
";
			}
		}
 
		document.getElementById('output').innerHTML = output;
	}
}

The end

So this is the object oriented XML parser. I hope that this is usefull one for you. I you have questions or remarks just drop me a note.

Share and Enjoy:
  • Twitter
  • Digg
  • Sphinn
  • del.icio.us
  • FriendFeed
  • Facebook
  • StumbleUpon
  • Google Bookmarks
  • email

Tags: ,

2 Comments to AJAX, an object oriented XML parser

Patrick
May 19, 2009 at 23:34

Hello, Do you have an example html page that puts this all together? That would be helpfu.

Arjan
May 20, 2009 at 8:17

Hi,

Don’t have an example in Englsih, but try this Dutch one. It’s an old one, but I think you get the point :-)

http://netters.nl/examples/tools/bible-search/

Leave a comment

About Arjan

Arjan Snaterse Hi, I'm Arjan Snaterse and in my daily life I'm working as SEO and Frontend manager at Jaludo. There I'm working on casual gaming sites like Funny games and Titter girl games.

In my spare time I'm developing websites in Wordpress or Typolight. HTML standards, semantics and CSS are words that make me happy. So if you need someone who converts your design (PSD) to HTML/Wordpress just contact me.