Reputation: 587
I have a PHP script that appears to be producing valid XML output, and I am attempting to pull this into the browser with an ajax XMLHttpRequest call.
After the ajax call is made, I can see in firebug that the request was succesful and the xml appears valid, but when I try to put the response into a variable I get an error saying the response is null.
Here is the PHP code:
<?php
$q=$_GET["q"];
$con = mysql_connect('address.com', 'dbnme', 'password');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sql01_5789willgil", $con);
$sql="SELECT * FROM place";
$result = mysql_query($sql);
$xmlResponse = "<?xml version='1.0' encoding='ISO-8859-1'?>\n";
$xmlResponse .= "<placeList>\n";
while($row = mysql_fetch_array($result))
{
$xmlResponse .= "<place>\n";
$xmlResponse .= "<title>". $row['title'] . "</title>\n";
$xmlResponse .= "<description>" . $row['description'] ."</description>\n";
$xmlResponse .= "<latitude>" . $row['latitude'] ."</latitude>\n";
$xmlResponse .= "<longitude>" . $row['longitude'] ."</longitude>\n";
$xmlResponse .= "<image>" . $row['image'] ."</image>\n";
$xmlResponse .= "</place>\n";
}
echo $xmlResponse;
mysql_close($con);
?>
And the offending JavaScript:
//Pull in the xml data for the bubbles
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
xmlDoc=xmlhttp.responseXML; //pull the xml into the DOM
var x = xmlDoc.getElementsByTagName("place"); //return the contents of the xml file (places) to an array called x
setupMap();
}
}
xmlhttp.open("GET","getPlaces.php",true);
xmlhttp.send();
Thankyou very much for any help!
Upvotes: 0
Views: 1770
Reputation: 47331
It seems you forget to close your root node
// ensure not output before this point
header("Content-type: text/xml"); // good practice
while($row = mysql_fetch_array($result))
{
...;
}
$xmlResponse .= "</placeList>\n";
echo $xmlResponse;
To ensure parse DOM successfully, an additional header to indicate response is a XML might necessary
Upvotes: 2
Reputation: 116170
Maybe the xml isn't valid after all. Try reading responseText
to see if you get any result at all. Also, PHP 's got a DOM object itself for generating xml. Using that will make it easier to create valid XML.
[edit]
As far as I can tell, you did at least forget </placelist>
at the end of the output.
And it might be a good idea to escape your values. A <
in the title will break your XML.
Upvotes: 1