This site is mobile accessible. Press the "Tap Here" button to use a different font-size.
Smartphone icons created by Freepik - Flaticon
AJAX can be used for interactive communication with an XML file.
The following example will demonstrate how a web page can fetch information from an XML file with AJAX:
Select a CD:
CD info will be listed here...
Select a CD: Bob Dylan
TITLE: Empire Burlesque
ARTIST: Bob Dylan
COUNTRY: USA
COMPANY: Columbia
PRICE: 10.90
YEAR: 1985
Select a CD: Bee Gees
TITLE: One night only
ARTIST: Bee Gees
COUNTRY: UK
COMPANY: Polydor
PRICE: 10.90
YEAR: 1998
Select a CD: Cat Stevens
TITLE: The very best of
ARTIST: Cat Stevens
COUNTRY: UK
COMPANY: Island
PRICE: 8.90
YEAR: 1990
When a user selects a CD in the dropdown list above, a function called "showCD()" is executed. The function is triggered by the "onchange" event:
<html>
<head>
<script>
function showCD(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getcd.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="">Select a CD:</option>
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bee Gees">Bee Gees</option>
<option value="Cat Stevens">Cat Stevens</option>
</select>
</form>
<div id="txtHint">CD info will be listed here...</div>
</body>
</html>
<?php
$q=$_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("cd_catalog.xml");
$x=$xmlDoc->getElementsByTagName('ARTIST');
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);
}
}
}
$cd=($y->childNodes);
for ($i=0;$i<$cd->length;$i++) {
//Process only element nodes
if ($cd->item($i)->nodeType==1) {
echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
echo($cd->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
?>
Eventually the navigation links, above, will be replaced by these (previous) and (next) buttons below.
Animated PHP icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon