
Using responseXML and the DOM instead of responseText
So far we have been looking at AJAX using an XML file, however we have really only been treating the XML file as any other text file. This could have been a .txt .htm or some text generated by a server side scripting engine (PHP, ASP etc.)
We were using:
XMLHttpRequest.responseText (for most browsers)
ActiveXObject.responseText (for Internet Explorer)
You will notice in the example from Part 2. that it takes the information in the xml document and turns it into a single string.
responseXML is similar in function to responseText, however rather than holding the data as a string of text, it includes the XML DOM structure (Document Object Model).
Having the XML DOM means that we can select text/data from within specific XML tags. Once selected, specific data can be updated to different parts of the HTML page (using HTML element ID's).
To use responseXML is very similar to responseText:
XMLHttpRequest.responseXML (for most browsers)
ActiveXObject.responseXML (for Internet Explorer)
In addition we have to specify which tag we are taking the data from using:
.getElementsByTagName('name').item(0).firstChild.data
where 'name' is the tag name in the XML file.
Example of some responseXML code:
This example uses:
receiveReq is the browser specific XMLHttpRequest object
div1 is the element ID to be updated in the HTML document
data1 is the tag in the XML file where the data is stored
Problems with IE (here we go again!!)
The responseXML object works in IE however... the file has to be sent to the browser with the HTTP header content type set as Content-Type: application/xml otherwise IE will throw a JavaScript error 'Object Expected'.
This means that your AJAX and XML files will not work with IE if they are stored in a folder on your local hard drive they need to be served by a web server (a local WAMP works fine).
responseXML Examples
Have a look at the following example at the end of this article that uses the responseXML object to dynamically update a number of HTML elements using data within the XML file.
So that's a basic introduction to AJAX. I'll be the first to admit that the examples aren't that exciting but it does show the basic function of AJAX and dynamically updating external data - something that seems to be glossed over on many web development sites. Have fun.
tobyonline
This is the newdata.xml file:
This is the html file:
This is a normal paragraph in the web page.
note: Drupal has added some extra paragraph tags in the above text box - extra points for spotting and removing them before you run your code :)