Processing XML Data from AJAX Responses with JavaScript - Using the responseXML property
(Page 3 of 4 )
As I stated in the previous section, I'm going to build a short PHP 5 script, which will have the capacity to fetch from MySQL, the database rows that you saw previously, which will finally be sent to the browser in XML format.
Having explained how this simple script will work, below I included its corresponding signature, so have a look at it, please:
// connect to MySQL
$db=new MySQL(array
('host'=>'host','user'=>'user','password'=>'password',
'database'=>'database'));
session_start();
!$_SESSION['counter']||$_SESSION['counter']>3?$_SESSION
['counter']=1:$_SESSION['counter']++;
$id=$_SESSION['counter'];
// run query
$result=$db->query("SELECT firstname,lastname,email,comments FROM
users WHERE id='$id'");
// send user data back to main page
$row=$result->fetchRow();
if($result->countRows()==1){
header('Content-Type: text/xml; charset=iso-8859-1');
echo '<?xml version="1.0" encoding="iso-8859-1"?>';
echo '<userdata>';
echo '<firstname>'.$row['firstname'].'</firstname>';
echo '<lastname>'.$row['lastname'].'</lastname>';
echo '<email>'.$row['email'].'</email>';
echo '<comments>'.$row['comments'].'</comments>';
echo '</userdata>';
}
Definitely, after studying the above PHP 5 script, you'll have to agree with me that things are getting really interesting at this point. As you can see, the script in question retrieves one database record at a time, based upon a simple session mechanism, and then echoes this data in basic XML format. Quite easy to grasp, right?
The purpose in doing this is to send to the client all the data fetched from the respective "Users" MySQL database table in a format (in this case, as XML) that will be extremely easy to parse, by utilizing some DOM scripting.
To prove the veracity of this concept, below I defined a brand new JavaScript function, which takes up the XML data sent by the previous script, and then displays neatly on the browser all the information about a user.
The signature of the JavaScript function is as follows:
function displayResults(userData){
var datacont=document.getElementById('datacontainer');
if(!datacont){return};
var firstName=userData.getElementsByTagName('firstname')
[0].firstChild.nodeValue;
var lastName=userData.getElementsByTagName('lastname')
[0].firstChild.nodeValue;
var email=userData.getElementsByTagName('email')
[0].firstChild.nodeValue;
var comments=userData.getElementsByTagName('comments')
[0].firstChild.nodeValue;
var fnh3=document.createElement('h3');
var lnh3=document.createElement('h3');
var emh3=document.createElement('h3');
var coh3=document.createElement('h3');
var fnpar=document.createElement('p');
var lnpar=document.createElement('p');
var empar=document.createElement('p');
var copar=document.createElement('p');
var div=document.createElement('div');
var cont=document.getElementById('container');
if(cont){cont.parentNode.removeChild(cont)};
div.setAttribute('id','container');
fnh3.appendChild(document.createTextNode('First Name'));
fnpar.appendChild(document.createTextNode(firstName));
lnh3.appendChild(document.createTextNode('Last Name'));
lnpar.appendChild(document.createTextNode(lastName));
emh3.appendChild(document.createTextNode('Email'));
empar.appendChild(document.createTextNode(email));
coh3.appendChild(document.createTextNode('Comments'));
copar.appendChild(document.createTextNode(comments));
div.appendChild(fnh3);
div.appendChild(fnpar);
div.appendChild(lnh3);
div.appendChild(lnpar);
div.appendChild(emh3);
div.appendChild(empar);
div.appendChild(coh3);
div.appendChild(copar);
datacont.appendChild(div);
setTimeout("sendHttpRequest
('get_user_data.php','displayResults',true)",5*1000);
}
As you can see, the prior "displayResults()" JavaScript function performs a few simple tasks to parse the user data that comes from the web server. In this case, this function utilizes a combination of the "responseXML" AJAX property and some common DOM methods for displaying on the browser the pertinent information for a specific user, in this way implementing a fully standard approach for processing AJAX responses.
It's fair to notice here that the previous JavaScript function may seem rather complex at first sight, but if you study its source code in more detail, you'll realize that it uses a few basic DOM methods to manipulate the web document tree and display the pertinent user data in the client.
Well, at this stage hopefully you grasped the logic that stands behind parsing AJAX responses that are served in XML format. As you saw earlier, this process is quite straightforward and can be performed easily with the assistance of the neat "responseXML" property.
Thus, considering the fact that you may want to see the complete source code corresponding to this sample AJAX application, in the last section of this tutorial I'll be listing this code. Having it all in one place will make it easy for you to copy it and paste it into your preferred code editor for further improvements.
To see the entire source code of this AJAX application, click on the link shown below and keep reading.
Next: Assembling the different modules of the AJAX application >>
More JavaScript Articles
More By Alejandro Gervasio