When a students selects a STU
in the dropdown list above, a function called "showSTU()
" is executed. The function is triggered by the "onchange" event :
<!DOCTYPE html>
<html>
<head>
<title>PHP - AJAX and XML</title>
</head>
<body>
<style type="text/css">
.cus_form{
padding:6px 15px;
border-radius:3px;
border:1px solid #0099da;
width:300px;
}
</style>
<script type="text/javascript">
function showSTU(str) {
if (str=="") {
document.getElementById("stu_details").innerHTML="";
return;
}
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 (this.readyState==4 && this.status==200) {
document.getElementById("stu_details").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","get_ajax_xml_data.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
Select Student :
<select name="students" class="cus_form" onchange="showSTU(this.value)">
<option value="">Select Student:</option>
<option value="Chanti">Chanti</option>
<option value="Ramana Reddy">Ramana Reddy</option>
<option value="Roja Reddy">Roja Reddy</option>
</select>
</form><br />
<div id="stu_details"><b>Student details will be listed here...</b></div>
</body>
</html>
The server called by the JavaScript above is a PHP file "get_ajax_xml_data.php".
The PHP script loads an XML document, " students.xml ", runs a query against the XML file, and returns the result as HTML :
<!DOCTYPE html>
<html>
<head>
<title>PHP - AJAX and XML</title>
</head>
<body>
<?php
$q=$_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("students.xml");
$x=$xmlDoc->getElementsByTagName('NAME');
for ($i=0; $i<=$x->length-1; $i++) {
//Process only element nodes
if ($x->item($i)->nodeType==1) {
if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
$y=($x->item($i)->parentNode);
}
}
}
$stu=($y->childNodes);
for ($i=0;$i<$stu->length;$i++) {
//Process only element nodes
if ($stu->item($i)->nodeType==1) {
echo("<b>" . $stu->item($i)->nodeName . ":</b> ");
echo($stu->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
?>
</body>
</html>
<NAME>
elements that matches the name sent from the JavaScript