Wednesday, 21 April 2021

AJAX Web Application for Reading Data from XML

 cdcatalog.xml

<?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
  <CD>
    <TITLE>Empire Burlesque</TITLE>
    <ARTIST>Bob Dylan</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>Columbia</COMPANY>
    <PRICE>10.90</PRICE>
    <YEAR>1985</YEAR>
  </CD>
  <CD>
    <TITLE>Hide your heart</TITLE>
    <ARTIST>Bonnie Tyler</ARTIST>
    <COUNTRY>UK</COUNTRY>
    <COMPANY>CBS Records</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1988</YEAR>
  </CD>
  <CD>
    <TITLE>Greatest Hits</TITLE>
    <ARTIST>Dolly Parton</ARTIST>
    <COUNTRY>USA</COUNTRY>
    <COMPANY>RCA</COMPANY>
    <PRICE>9.90</PRICE>
    <YEAR>1982</YEAR>
  </CD>
</CATALOG>

readxml.html

<!DOCTYPE html>
<html>
<head>
<script>
function loadDoc() 
{
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() 
{
if (this.readyState == 4 && this.status == 200) 
{
var xmlDoc = xhttp.responseXML;
var table="<table border='1'><tr><th>Title</th><th>Price</th><th>Year</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.lenght; i++) 
{
table += "<tr><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue +
"</td><td>"+
x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue +
"</td></tr>"
}
table+="</table>";
document.getElementById("demo").innerHTML = table;
}
};
xhttp.open("GET", "cdcatalog.xml", true);
xhttp.send();
}
</script>
</head>
<body onload="loadDoc()">
<h1>Reading XML Data</h1>
<div id="demo"></div>
</body>
</html>

AJAX Web Applications with Database Access

 Cricket Score Display using AJAX

score.html

<!DOCTYPE html>
<html>
<head>
<script>
function viewScore()
{
request=new XMLHttpRequest();
request.open("GET","dbaccess.php",true);
request.send();
try
{
request.onreadystatechange=function()
{
if(request.readyState==4 & request.status=200)
{
document.getElementById('score').innerHTML=request.responseText;
}
};

}
catch(e)
{
alert("Unable to connect to server");
}
}
setInterval(viewScore,1000);
</script>
</head>
<body>
<h1>Retrive data from database using AJAX</h1>
<div id="score"><h2></h2></div>
</body>
</html>



dbaccess.php

<?php
// Create connection
$conn = new mysqli("localhost","abcd","1234", "test");

// Check connection
if ($conn->connect_error) 
{
    die("Connection failed:".$conn->connect_error);
}
$sql = "SELECT * FROM IPL";
$result = $conn->query($sql);
if ($result->num_rows > 0) 
{
    // output data of each row
    while($row = $result->fetch_assoc()) 
    {
        echo "Score:".$row["score"]."/".$row["wicket"]." Overs:".$row["over"];
    }
else 
{
    echo "0 results";
$conn->close();
?>