Getting XML Data from Server Using AJX

Friday, June 27, 2008

Previously, we use AJAX to receive data from server using the responseText property, it's quite usefull but what if you want to get a complicated data like a bunch of names, addresses, numbers, and many more information in a single request? Sure, you can format your responseText, but why bother if you can use the responseXML property?

Accessing the responseXML will get you a response of HTTP request as XML DOM objects, and this only happen if the XML returned by the server is a valid XML, otherwise you get null.

Here's how we do it.

First, an example of XML file generated by PHP, you can generate more complex with database-driven data, but here's I just a simple plain XML.

<?php
header('Content-type: text/xml');
?>
<students>
 <student year="1999">
  <name>John Smith</name>
  <ssn>23132452</ssn>
 </student>
 <student year="2000">
  <name>Jane Smith</name>
  <ssn>23132453</ssn>
 </student>
</students>
and the javscript code to extract data from XML file.
function getXMLHttp() {
var XMLHttp = null;
if (window.XMLHttpRequest) {
  try {
    XMLHttp = new XMLHttpRequest();
  } catch (e) { }
} else if (window.ActiveXObject) {
  try {
    XMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) { }
  }
}
return XMLHttp;
}

var XMLHttp = getXMLHttp();
XMLHttp.open("GET", "getstudents.php");
XMLHttp.onreadystatechange = function(){
if (XMLHttp.readyState == 4) {
  var xml = XMLHttp.responseXML;
  var student = xml.getElementsByTagName("student")[0];
  var year= student.getAttribute("year");
 var name, ssn;
 for (var i=0; i<student.childNodes.length; i++) {
    if (student.childNodes[i].nodeName == "name") {
      name = student.childNodes[i].firstChild.nodeValue;
    } else if (student.childNodes[i].nodeName == "ssn") {
      ssn= student.childNodes[i].firstChild.nodeValue;
    }
  }
  window.alert(name + " / " + ssn + " / " + year);
}
};
XMLHttp.send(null);
Screenie of the result


I'll write about using documentElement and JSON to do the same thing, but in an easier way, later. For now, I hope the code above suffices.

0 comments: