PHP - AJAX
Learn PHP Classic by building a web site from scratch.
Part V: Displaying Data Using AJAX.
What We Will Do
In this chapter we will:
- Displaing data from the database using AJAX
Create an AJAX Server Page
In your web folder (DemoPHP), create a new PHP file named "getCustomers.php".
Put the following code inside the ASP file:
getCustomers.php
<?php
header('Content-Type: text/html; charset=ISO-8859-1');
//create an ADO connection and open the database
$conn = new
COM("ADODB.Connection");
$conn->open("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\WebData\Northwind.mdb");
//execute an SQL statement and
return a recordset
$rs = $conn->execute("SELECT CompanyName, City,
Country FROM Customers");
$num_columns = $rs->Fields->Count();
echo "<table border='1'>";
echo
"<tr><th>Name</th><th>City</th><th>Country</th></tr>";
while (!$rs->EOF)
//looping through the recordset (until End Of File)
{
echo "<tr>";
for ($i=0; $i < $num_columns; $i++) {
echo "<td>" .
$rs->Fields($i)->value . "</td>";
}
echo "</tr>";
$rs->MoveNext();
}
echo "</table>";
//close the recordset and the database
connection
$rs->Close();
$rs = null;
$conn->Close();
$conn =
null;
?>
The file above is a standard PHP file, returning only an HTML table.
Create an AJAX Browser Page
In your "DemoPHP" folder, create a new file named "Ajax.html".
Put the following code inside the file:
Ajax.html
<!DOCTYPE html>
<html>
<head>
<title>ASP Demo</title>
<link
href="Site.css" rel="stylesheet">
</head>
<body>
<div id="main">
<h1>Customers</h1>
<div id="t01"></div>
</div>
<script>
var xmlhttp;
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 (xmlhttp.readyState==4 &&
xmlhttp.status==200)
{
document.getElementById("t01").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getCustomers.php",true);
xmlhttp.send();
</script>
</body>
</html>
Try it Yourself »
Congratulations
You have created your first data page using AJAX.
Thank You For Helping Us!
Your message has been sent to W3Schools.
Close [X]