Site Navigation
AJAX Series: Tutorial #3 - The X in AJAX stands for XML
written by vegu on 29 Jan, 2007 10:55:01
The X in AJAX stands for XML, however most AJAX tutorials i come across online only seem to deal with the raw content responseText property.
I imagine it is because it is sufficient most of the time. However using XML as transfer protocol can be an advantage because you do not need to parse the content manually and can work with the data in a structured way right way.
Whenever the content type of the content received by the xml request is xml the responseXML property is set. It holds a DOM object created from the XML received that we can walk through as we would do with any other DOM object.
Let's start by making a XML document for our client application to request. We do this by making a simple php script.
Contents of xml.php:
<?
header('Content-Type: text/xml');
?>
<tutorial>
<alert msg="Hello World!" />
</tutorial>
Okay now when we request this file using ajax it will see that it's holding XML data and the responseXml property of the XMLHttpRequest object will be set upon receiving the data from the server.
The ajax_new() function is a function i introduced in the first AJAX tutorial on this site, it simply returns a XMLHttpRequest with cross browser support, if you have your own function already, use it.
ajax = ajax_new();
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
var xml = ajax.responseXML;
var tutorial = xml.firstChild;
var n,N;
for(n in tutorial.childNodes) {
N = tutorial.childNodes[n];
if(N.nodeName == 'alert') {
alert(N.getAttribute('msg'));
}
}
}
}
ajax.open('GET', 'xml.php', true);
ajax.send(null);
That's basically it, the way AJAX was intended to be used :)
So why use it instead of just reading data from responseText? Well both ways have their advantages and disadvantages. It also depends on the complexity of your project.
Using XML as a protocol saves you the time from having to develop your own protocol structure. However if bandwidth is an issue – for example if youre making a web game that updates in real time – you might want to use a bitmask style protocol. Meaning you use delimiters for operations and arguments, but ill explain that further in the next tutorial.
With XML you're provided with a structured way of handling server client communication.
For example lets say you send an AJAX request to a php script, the php script attempts to connect to a database, but the connection fails for whatever reason. PHP then prints the XML data accourdingly
<document>
<error msg="mySQL could not connect, OH MY GOD" />
</document>
And you can easily process that data on the client side. You could get all error elements or you could just work through all elements in the tree and handle them any way you like.
Related Posts
Your Comment
Comments
No comments yet.