Ajax - Returning Data as XML

Elsewhere on this site we've discussed the responseText property of our XMLHTTPRequest object. This returns information from the server (as requested by an Ajax call) as a text string, which we can process however we see fit.

In instances where we simply wish to update the contents of a page element - a <DIV>, for instance - this is a straightforward way to do it. Sort of Like 'Ajax' without the 'ax', I suppose! In some quarters this is becoming known as AHAH (Asynchronous HTML and HTTP). If you wish to learn more about it, you'll find a page on AHAH on this site.

Using the X Factor

Our XMLHTTPRequest object does, however, have another way of returning data to us, in the form of the responseXML property. Let's assume that we simply wish to return the contents of a valid XML file which is resident on our server:

<?xml version="1.0" ?>
<fullname>
    Joe Bloggs
</fullname>

This time, we use within our response handler function the responseXML property of our XMLHTTPRequest. Assuming that our XMLHTTPRequest object is called http, then, the following code in the response handler will use Javascript's DOM parsing abilities to extract the data from the <fullname> element and display it in an alert box:

var ourdoc = http.responseXML; var full_name = ourdoc.getElementsByTagName('fullname').item(0); alert(full_name.firstChild.data);

For those not familiar with the DOM (Document Object Model) and the Javascript functions that are available to manipulate it, there'll be a tutorial appearing on this site shortly.

 


Before using any software from this site, please see the Terms



3 Users Online.

All of the code and information on this site is provided free of charge (but without warranty).
If you feel that the site has been useful, you may care to donate a little toward the running of the site and the development of further projects?