View Full Version : Trouble parsing XML with Javascript

10-20-2010, 05:16 PM
Hi guys,

I'm having trouble parsing an XML response with Javascript. Whenever I create an object to hold the response as responseText, I have no problem seeing all of the XML, but whenever I create the object and hold the response as responseXML it seems to fail (null).

The php script I created outputs XML directly with echo statements. I do have some formatting in it as well (\n and \r). I've verified the output XML looks correct (no missing or malformed tags). Could the formatting be the problem? Should I output the XML via PHP another way?

If this makes no sense, the idea behind the site is that a user has a dynamic dropdown element that allows them to choose a course they are a teaching assistant for, which will then populate a table based upon the response from the PHP script. I had the script output XML instead of directly writing HTML because I thought this would make the code more modular. (The client could do the formatting as opposed to having to rewrite the PHP everytime something changes or is added) Is this a bad idea?

Here's a simple example of what I'm doing with the Javascript. Additionally, I noticed (via Firebug) that xmlDoc is null for some reason. Any and all help is appreciated. Thanks in advance :)


<script type="text/javascript">
if (window.XMLHttpRequest)
//new browser
xmlhttp = new XMLHttpRequest();
//IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

xmlhttp.open("GET", "get_data.php?id=knobel", true);

if (xmlhttp.readyState==4 && xmlhttp.status==200)
document.getElementById("mydiv").innerHTML = xmlhttp.responseText;

document.write("test"); //doing this to see if statements are failing

xmlDoc = xmlhttp.responseXML;

document.write("xmldoc good"); //doing this to see if statements are failing

x = xmlDoc.getElementsByTagName("class"); //this seems to fail, every time


<span id="mydiv">Old div</span><br>
<span id="mydiv2">Other div</span><br>

10-27-2010, 10:29 PM
What does your get_data.php look like. Are you setting the correct response header type?

header ("Content-Type:text/xml");


11-12-2010, 03:10 AM
Hi, I am having a very similar problem, in that responseText is populated by correctly formated XML but responseXML is null... I am setting the header in PHP to text/xnl as required... see my recent thread here:


11-12-2010, 10:16 AM
try opening your xml file in firefox to see if it is well formed an throws no errors