Reputation: 351
Seems my javascript isn't picking up on my php sending back an xml document. php code:
$domtree = new DOMDocument('1.0', 'UTF-8');
/* append it to the document created */
$xmlRoot = $domtree->appendChild($domtree->createElement("root"));
foreach (glob('./img/photos/*.*') as $filename) {
//echo $filename;
$xmlRoot->appendChild($domtree->createElement("image",$filename));
}
/* get the xml printed */
echo $domtree->saveXML();
The output of the code above is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<root><image>./img/photos/2012-02-26 17.02.12.jpg</image>
<image>./img/photos/2012-03-09 08.21.48.jpg</image>
<image>./img/photos/2012-07-21 14.09.39.jpg</image>
<image>./img/photos/2012-07-25 15.25.17.jpg</image>
<image>./img/photos/2012-08-04 17.54.38.jpg</image>
<image>./img/photos/2012-08-04 23.36.30.jpg</image>
<image>./img/photos/2012-08-06 06.08.43.jpg</image>
<image>./img/photos/2012-08-07 20.57.34.jpg</image>
<image>./img/photos/2012-08-09 20.40.11.jpg</image>
<image>./img/photos/2012-08-25 20.54.05.jpg</image>
<image>./img/photos/2012-09-07 11.19.50.jpg</image>
<image>./img/photos/2012-09-08 15.53.27.jpg</image>
<image>./img/photos/2013-01-30 19.19.16.jpg</image>
<image>./img/photos/2013-01-31 09.48.39.jpg</image></root>
Calling this with AJAX, when I call AJAXRequest.responseXML i get null back.
EDIT: AJAX Request Code:
function requestImages()
{
request=new XMLHttpRequest();
request.open("GET", "getPhotos.php");
request.onreadystatechange=showPhotos;
request.send();
}
function showPhotos()
{
if ((request.readyState == 4)) {
doc=request.responseXML; // This returns null
}
}
Upvotes: 2
Views: 109
Reputation: 2796
If you are not using any third party library, try this kind of code snippet (modify it according to your requirement)
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
Note that it is using request.responseText and it will definitely get the returned xml if you will add content type as header("Content-type: text/xml");
in your header
UPDATE
To parse the xml, you can use the below code snippet:
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {} //use this for some processing at run time
Upvotes: 0
Reputation: 11016
Try sending the content type in php so AJAX know that is a xml and parse it (remember that this must be done before any echo
):
header("Content-Type: text/xml");
This can also be forced directly in javascript (with overrideMimeType()
) but is better done in php.
Upvotes: 1