AJAX Program
AJAX Program
The following example will demonstrate how a web page can fetch information from a database
with AJAX:
The database table we use in the example above looks like this:
Example Explained
In the example above, when a user selects a person in the dropdown list above,
a function called "showUser()" is executed.
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
xmlhttp.onreadystatechange = function() {
document.getElementById("txtHint").innerHTML =
this.responseText;
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
</select>
</form>
<br>
</body>
</html>
Code explanation:
First, check if person is selected. If no person is selected (str == ""), clear the
content of txtHint and exit the function. If a person is selected, do the following:
The source code in "getuser.php" runs a query against a MySQL database, and
returns the result in an HTML table:
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
table, td, th {
padding: 5px;
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','peter','abc123');
if (!$con) {
}
mysqli_select_db($con,"ajax_demo");
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "</tr>";
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
Explanation:
When the query is sent from the JavaScript to the PHP file, the following
happens: