Jump to content

Parsing responseXML


mathieu
 Share

Recommended Posts

Hi, I'm trying to extract some specific elements (tags) from an XML document which is the result of an ajax query.However, I cannot get any element. Below the alert function displays '0', while the XML document does have 3 'myTag' tags... Any help would be much appreciated Thanks, M.

	var result = $.ajax({	 url: 'server.php',	 dataType: 'XML',	 async: false	}); 	var myArray = $(result.responseXML).find('myTag');	alert(myArray.length);

Link to comment
Share on other sites

OK, now I get the thing: the php code was wrong:

$xmlDoc = new DOMDocument('1.0', 'iso-8859-1');$xmlDoc->loadXML($xml); //$xml is the string containing the XML codeecho $xmlDoc->saveXML();

I guess the "echo" function is the problem. I replaced it with return but it's not better.How can I transfer some XML code from the server to the web browser with PHP? Thanks

Edited by mathieu
Link to comment
Share on other sites

saveXML returns a string, so echoing the string will be fine. But if you're sending XML output, you need to also send a content-type header that tells the browser that the content type is application/xml. That will cause it to go into the responseXML property.

Link to comment
Share on other sites

I've add such a header and now the output is clearly recognized as XML by the browser, which was obviously not the case before.However it looks like the XML is still in responseText, not responseXML: Javascript:

	var resultat = $.ajax({	 url: 'serveur.php?serie=' + serie,	 dataType: 'XML',	 async: false	});	var noms = $(resultat.responseXML).find('photographie');	alert('Number of photographie elements: ' + noms.length + '\n\n' + resultat.responseText);

Output of the alert function:

Number of photographie elements: 0<?xml version="1.0" encoding="iso-8859-1"?><serie>  <photographie>	<nom>_DSC4689</nom>	<format>3_2</format>  </photographie>  <photographie>	<nom>_DSC2359</nom>	<format>3_2</format>  </photographie>  <photographie>	<nom>_DSC4632</nom>	<format>3_2</format>  </photographie></serie>

I guess there is a problem in the Javascript code, isn't it? Thanks

Link to comment
Share on other sites

Hmm, I'm not sure how jQuery deals with XML. Try this to see whether there's a mistake with the Javascript or with the XML document itself:

var noms = resultat.responseXML.getElementsByTagName("photographie");

Link to comment
Share on other sites

Hi, Thanks for your answer and sorry for my late response. I've tested handling the "photographie" tags with the getElementsByTagName() function rather than the jQuery find() function, as you proposed.There is no display anymore, the alert() function simply doesn't work. I'm not sure to know what we can conclude of this experiment... How do you usually exchange data between server and browser with PHP and JavaScript? ThanksMathieu

Link to comment
Share on other sites

Make sure something else has not messed up. I don't like that alert no longer works. Then try this:

var resultat = $.ajax({    url: 'serveur.php?serie=' + serie,    dataType: 'xml',    async: false,    success: function (data) {        var noms = $(data).find('photographie');        alert(noms.length);    }});

Link to comment
Share on other sites

Hmmm... I fear it doesn't work either. There is simply no display. I guess something's wrong in the data sent by the serveur. I was assuming the data were good, because the responseText() function does display the right XML output (cf. above). Maybe you will be able to spot an obvious mistake in the PHP code?

<?phpheader('Content-type: application/xml');//Connexion à la base de données$connexion = mysqli_connect('localhost','root','root','Photographies');if(mysqli_connect_errno($connexion)) {echo mysqli_connect_error();}//Récupération de l'id de la série, passé dans l'URL$serie=$_GET["serie"];//Requête des photos de cette série$resultatRequete = mysqli_query($connexion,"SELECT Nom,Format FROM Photographies WHERE Serie=".$serie." ORDER BY OrdreDansSerie ASC"); //Construction du Document XML$xmlDoc = new DOMDocument('1.0', 'iso-8859-1');$xmlDoc->formatOutput = true;$root = $xmlDoc->createElement('serie');$root = $xmlDoc->appendChild($root);while($row = mysqli_fetch_array($resultatRequete)) {  $photographie = $xmlDoc->createElement('photographie');  $photographie = $root->appendChild($photographie);  $nom = $xmlDoc->createElement('nom');  $nom = $photographie->appendChild($nom);  $text = $xmlDoc->createTextNode($row['Nom']);  $text = $nom->appendChild($text);  $format = $xmlDoc->createElement('format');  $format = $photographie->appendChild($format);  $text = $xmlDoc->createTextNode($row['Format']);  $text = $format->appendChild($text);} echo $xmlDoc->saveXML();mysqli_close($connexion);?>

ThanksM.

Link to comment
Share on other sites

I checked the javascript I sent you with the XML you posted in #7, and the same content-type header. I also validated the XML at W3C. It's fine. If that is the same output that your PHP produces, then it should be OK. What do you mean when you write this: "There is simply no display."? By any chance are you using MSIE? Older versions had problems recognizing XML text as an XML document; I assumed jQuery used one of the known workarounds. As a last resort, you could always convert the string.

Edited by Deirdre's Dad
Link to comment
Share on other sites

OK. Here are the two documents I used, exactly. I doubt the jQuery version matters. Tested in FF10 and IE8. HTML

<!DOCTYPE html><html>	<head>		<meta  http-equiv="Content-Type" content="text/html; charset=utf-8">		<title></title>		<script type="text/javascript" src="jquery-1.9.1.min.js"></script>		<script type="text/javascript">			window.onload = function () {				var resultat = $.ajax({					url: 'serveur.php',					dataType: 'xml',					async: false,					success: function (data) {						var noms = $(data).find('photographie');						alert(noms.length);					}				});			}		</script>	</head>	<body>	</body></html>

PHP

<?php $doc = '<?xml version="1.0" encoding="UTF-8"?><serie>  <photographie>		<nom>_DSC4689</nom>		<format>3_2</format>  </photographie>  <photographie>		<nom>_DSC2359</nom>		<format>3_2</format>  </photographie>  <photographie>		<nom>_DSC4632</nom>		<format>3_2</format>  </photographie></serie>'; header("Content-Type: application/xml");echo $doc; ?>

Edited by Deirdre's Dad
Link to comment
Share on other sites

Well, if it does work on your platform, that's already a good point. So I guess the output is "3". No, I don't use MSIE. I'm using Chrome, Firefox and Safari under Mac OS X. Yes, I checked and the PHP code produces the correct XML as an output. The browser recognizes it as XML, since it says "This XML file does not appear to have any style information associated with it. The document tree is shown below." By "no display" I mean that when I run the JavaScript, I get a blank page as a result, with no writtings... Yes, indeed the most robust way is maybe to interpret the output of the server as a text, then load it in a DOM object and parse it. Is that what you mean? ThanksM.

Link to comment
Share on other sites

Yes, indeed the most robust way is maybe to interpret the output of the server as a text, then load it in a DOM object and parse it. Is that what you mean?
I meant that as a last resort. The solution you've been trying should be robust enough. If you want to post all your code, maybe one of us can see something else that's affecting the process. A live link would be ideal. You could even PM me the address if you don't want the whole world to see it.
Link to comment
Share on other sites

Thanks for your proposal. I wish I could send you a live link, but it looks like my online platform is not fully settled now. I'm trying to fix this right now, but in the meantime, please find below the full code. Sorry for the special characters, we French people use them a lot... :) serveur.php:

<?phpheader('Content-type: application/xml');//Connexion à la base de données$connexion = mysqli_connect('localhost','root','root','Photographies');if(mysqli_connect_errno($connexion)) {echo mysqli_connect_error();}//Récupération de l'id de la série, passé dans l'URL$serie=$_GET["serie"];//Requête des photos de cette série$resultatRequete = mysqli_query($connexion,"SELECT Nom,Format FROM Photographies WHERE Serie=".$serie." ORDER BY OrdreDansSerie ASC"); //Construction du Document XML$xmlDoc = new DOMDocument('1.0', 'iso-8859-1');$xmlDoc->formatOutput = true;$root = $xmlDoc->createElement('serie');$root = $xmlDoc->appendChild($root);while($row = mysqli_fetch_array($resultatRequete)) {  $photographie = $xmlDoc->createElement('photographie');  $photographie = $root->appendChild($photographie);  $nom = $xmlDoc->createElement('nom');  $nom = $photographie->appendChild($nom);  $text = $xmlDoc->createTextNode($row['Nom']);  $text = $nom->appendChild($text);  $format = $xmlDoc->createElement('format');  $format = $photographie->appendChild($format);  $text = $xmlDoc->createTextNode($row['Format']);  $text = $format->appendChild($text);} echo $xmlDoc->saveXML();mysqli_close($connexion);?>

client.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head>  <title></title>  <script src="http://code.jquery.com/jquery-latest.js"></script>  <script>    //Attention : ce fichier doit être appelé depuis l'url http://localhost:8888/client.html   $(document).ready(function(){	//Serie	var serie = 1;	//AJAX	var resultat = $.ajax({	 url: 'serveur.php?serie=' + serie,	 dataType: 'XML',	 async: false	 success: function (data) {			var noms = $(data).find('photographie');		   alert(noms.length);	 }	});   });  </script></head><body></body></html>

ThanksM.

Link to comment
Share on other sites

Thanks for your proposal. I wish I could send you a live link, but it looks like my online platform is not fully settled now. I'm trying to fix this right now, but in the meantime, please find the full code below and attached. Sorry for the special characters, we French people use them a lot... :) serveur.php:

<?phpheader('Content-type: application/xml');//Connexion à la base de données$connexion = mysqli_connect('localhost','root','root','Photographies');if(mysqli_connect_errno($connexion)) {echo mysqli_connect_error();}//Récupération de l'id de la série, passé dans l'URL$serie=$_GET["serie"];//Requête des photos de cette série$resultatRequete = mysqli_query($connexion,"SELECT Nom,Format FROM Photographies WHERE Serie=".$serie." ORDER BY OrdreDansSerie ASC"); //Construction du Document XML$xmlDoc = new DOMDocument('1.0', 'iso-8859-1');$xmlDoc->formatOutput = true;$root = $xmlDoc->createElement('serie');$root = $xmlDoc->appendChild($root);while($row = mysqli_fetch_array($resultatRequete)) {  $photographie = $xmlDoc->createElement('photographie');  $photographie = $root->appendChild($photographie);  $nom = $xmlDoc->createElement('nom');  $nom = $photographie->appendChild($nom);  $text = $xmlDoc->createTextNode($row['Nom']);  $text = $nom->appendChild($text);  $format = $xmlDoc->createElement('format');  $format = $photographie->appendChild($format);  $text = $xmlDoc->createTextNode($row['Format']);  $text = $format->appendChild($text);} echo $xmlDoc->saveXML();mysqli_close($connexion);?>

client.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head>  <title></title>  <script src="http://code.jquery.com/jquery-latest.js"></script>  <script>    //Attention : ce fichier doit être appelé depuis l'url http://localhost:8888/client.html   $(document).ready(function(){	//Serie	var serie = 1;	//AJAX	var resultat = $.ajax({	 url: 'serveur.php?serie=' + serie,	 dataType: 'XML',	 async: false	 success: function (data) {			var noms = $(data).find('photographie');		   alert(noms.length);	 }	});   });  </script></head><body></body></html>

ThanksM.

client.html

serveur.php

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...