I am new to AJAX. I'm trying to write code that will extract from an XML file and then display the results. Keep getting a syntax error.

HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Extract Data from an XML file</title>

<script type="text/javascript" language="javascript">
<!--The object detection code -->
 var req = null;
// Is there support for native XHR object?: IE7+, Firefox, Safari, Opera
 if (window.XMLHttpRequest)
{
 req = new XMLHttpRequest();
 //create an XMLHttpRequest object
}

 else if (window.ActiveXObject)
 //check for Version 6
{
 req = new ActiveXObject('MSXML2.XMLHTTP.6.0');
 //create an ActiveX XMLHTTP component
}
 if (!req)
{
req = new ActiveXObject('MSXML2.XMLHTTP');
//fallback to version 3
}

function goXml()
{

	if (req)
	{
	//Request data to be retrieved from the server

req.onreadystatechange = function() {

if(req.readyState == 4 && req.status == 200) {
    var xmlDoc= req.responseXML;
    var musicianInfo = xmlDoc.getElementsByTagName("*");
    for (i=0;i<musicianInfo.length;i++) {
                  document.getElementById('XmlData').innerHTML=musicianInfo[i];
         		      }

        }
 
else {
     req = false;
     }
 }

}
req.open("GET", "MusicianList.xml", true);
req.send(null);
}


//-->
</script>
</head>

<body>
<p>Click the button to show the list: <input type="button" value="Display the List" onClick="goXml()"></p>
<div id="XmlData" style="border:1px solid black;height:40;width:300">
</div>


</body>
</html>

Xml file:

<?xml version="1.0" encoding="utf-8" ?> 
- <musicians>
- <musician>
  <name>Bruce Springsteen</name> 
  <genre>Rock</genre> 
  <hitsong>Born in the USA</hitsong> 
  </musician>
- <musician>
  <name>B.B. King</name> 
  <genre>Blues</genre> 
  <hitsong>The Thrill Is Gone</hitsong> 
  </musician>
- <musician>
  <name>Tim McGraw</name> 
  <genre>Country</genre> 
  <hitsong>Live Like You Were Dying</hitsong> 
  </musician>
- <musician>
  <name>Gordon Lightfoot</name> 
  <genre>Folk</genre> 
  <hitsong>Carefree Highway</hitsong> 
  </musician>
- <musician>
  <name>Glenn Miller</name> 
  <genre>Big Band</genre> 
  <hitsong>In The Mood</hitsong> 
  </musician>
  </musicians>

My hangup seems to be with this piece:

req.onreadystatechange = function() {

if(req.readyState == 4 && req.status == 200) {
    var xmlDoc= req.responseXML;
    var musicianInfo = xmlDoc.getElementsByTagName("*");
    for (i=0;i<musicianInfo.length;i++) {
                  document.getElementById('XmlData').innerHTML=musicianInfo[i];
         		      }

My intention was to access all of the tags (name, genre, and hitsong) in the XML file. Thought that var musicianInfo = xmlDoc.getElementsByTagName("*"); would do that. Then, loop through each tag and display the result.

Why isn't it working?

Recommended Answers

All 4 Replies

I've done a lite modification in your xml and html code.

Here's the overall results:

MusicianList.xml

<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<!DOCTYPE musicians [
<!ELEMENT musicians (musician*)>
<!ELEMENT musician (#PCDATA|name|genre|hitsong)*>
<!ELEMENT name (#PCDATA)>
<!ELEMENT genre (#PCDATA)>
<!ELEMENT hitsong (#PCDATA)>
]>
<musicians>
<musician>
<name>Bruce Springsteen</name> 
<genre>Rock</genre> 
<hitsong>Born in the USA</hitsong> 
</musician>
<musician>
<name>B.B. King</name> 
<genre>Blues</genre> 
<hitsong>The Thrill Is Gone</hitsong> 
</musician>
<musician>
<name>Tim McGraw</name> 
<genre>Country</genre> 
<hitsong>Live Like You Were Dying</hitsong> 
</musician>
<musician>
<name>Gordon Lightfoot</name> 
<genre>Folk</genre> 
<hitsong>Carefree Highway</hitsong> 
</musician>
<musician>
<name>Glenn Miller</name> 
<genre>Big Band</genre> 
<hitsong>In The Mood</hitsong> 
</musician>
</musicians>

main.html

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<?xml-stylesheet type="text/css" href="#ccs21" media="all"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html id="xhtml10S" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://www.w3.org/2005/10/profile">
<!--[if IE]>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<![endif]-->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title>Free Live Help!</title>
<style id="css21" type="text/css" media="all">
/* <![CDATA[ */
table {
  border : none;
  width : 100%;
  border-collapse : collapse; }

th {
  color : #708090;
  background-color : #fff;
  vertical-align : middle;
  border-bottom : 1px solid #ddd;
  border-right : 1px solid #ddd;
  text-align : center;
  font-weight : normal;
  width : 30%; }

td {
  border : 1px solid #ccc;
  background-color : #f0ffff; 
  width : auto;
  color : #708090;
  padding : 1% 0 1% 2%; }

th[colspan] {
  text-indent : 1em;
  width : 100%;
  border-top : 1px solid #ccc;
  border-bottom : 1px solid #ccc;
  letter-spacing : 2px;
  color : #708090;
  height : 20px;
  background-color : #f7f7f7;
  text-align : left; }

div#XmlData {
  border : 1px solid #ccc;
  height :40px;
  margin-top : 2em; 
  width: 300px;
  padding : 2%; }
/* ]]> */
</style>
<script id="script15" type="text/javascript">
// <![CDATA[
var req;
var handleRequest = function() { 
   var div = (( document.getElementById ) ? document.getElementById("XmlData") : document.all.XmlData );

   var xmlDoc = req.responseXML;

   if (( req.readyState === 4 ) || ( req.readyState === "complete" )) {
      // if ( req.status === 200 ) {
    var table = "";
    table += "<table frame=\"void\" rules=\"none\" summary=\"XML Documents Sample\">";
    var musicianInfo =  xmlDoc.getElementsByTagName("*"); 
    var tLen = musicianInfo.length;

musician :

   for ( var y = 0; y < tLen; y++ ) {
      if ( musicianInfo[ y ].nodeName === "name" ) {
      table += "<tr>";
      table += "<th colspan=\"2\">" + musicianInfo[ y ].childNodes[ 0 ].nodeValue + "</th>";
      table += "</tr>"; 
      continue musician; }

      if ( musicianInfo[ y ].nodeName === "genre" ) {
      table += "<tr>";
      table += "<th>Genre : </th>"
      table += "<td>" + musicianInfo[ y ].childNodes[ 0 ].nodeValue + "</td>\n</tr>\n";
     continue musician; }
      if ( musicianInfo[ y ].nodeName === "hitson" ) {
      table += "<tr>\n";
      table += "<th>Hitsong : </th>";
      table += "<td>" + musicianInfo[ y ].childNodes[ 0 ].nodeValue + "</td>";
      table += "</tr>\n";
      continue musician; } 
   } table += "</table>";
 div.innerHTML = table;           
      // }
      }
   };

var goXml = function() {
   req = null;
   method = "GET";
   try {
      if ( window.XMLHttpRequest ) {
      req = new XMLHttpRequest();
   } else if ( window.ActiveXObject ) {
         try {
         req = new ActiveXObject("Microsoft.XMLHTTP");
         } catch( e1 ) {
         req = new ActiveXObject("Msxml2.XMLHTTP");
         }
      }
   } catch( e2 ) {
   (( window.createRequest ) ? req = window.createRequest() : req = null );
   }
   (( req.overrideMimeType ) ? req.overrideMimeType("text/xml") : req );
   if ( req !== null ) {             req.onreadystatechange = handleRequest;
   req.open( method, "MusicianList.xml", true );
   (( req.setRequestHeader && method === "POST" ) ?  req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") : req ); 
   req.send( null );
   } else {
      alert("\nYour browser does not support AJAX Request!"); 
   }
};
// ]]>
</script>
</head>
<body>
<div id="main">
<p>Click the button to show the list: <button id="btn" name="btn" onclick="goXml();">Display the List &darr;</button></p>
<div id="XmlData"></div>
</div> 
</body>
</html>

hope it helps...

Thanks essential! I'm not the original poster but I found this very helpful. Far better then what's available in most Ajax tutorials.

You just post it as a tutorial example somewhere so its more permanent then this post.

Dave

Also, a quick question: Does this get used by the JavaScript or is it just for clarity for a human reading it?

<!DOCTYPE musicians [
<!ELEMENT musicians (musician*)>
<!ELEMENT musician (#PCDATA|name|genre|hitsong)*>
<!ELEMENT name (#PCDATA)>
<!ELEMENT genre (#PCDATA)>
<!ELEMENT hitsong (#PCDATA)>
]>

And there's just a typo in the code: hitson -> hitsong

Hi davepc,

Thank you for appreciating my work.

<!DOCTYPE musicians [ 
<!ELEMENT musicians (musician*)> 
<!ELEMENT musician (#PCDATA|name|genre|hitsong)*> 
<!ELEMENT name (#PCDATA)> <!ELEMENT genre (#PCDATA)> 
<!ELEMENT hitsong (#PCDATA)> ]>

It does not participate in any events (or function's) execution inside javascript. i've just included those DTDs for clarity and definition of all items inside the XML Document.

And also keeping the W3C standards for each document.

Once again, thank you for your time and comments...

essential

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.