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 a database.
The following example will demonstrate how a web page can fetch information from a database with AJAX:
Select a customer: Alfreds Futterkiste
CustomerID | ALFKI |
CompanyName | Alfreds Futterkiste |
ContactName | Maria Anders |
Address | Obere Str. 57 |
City | Berlin |
PostalCode | 12209 |
Country | Germany |
Select a customer: North/South
CustomerID | NORTS |
CompanyName | North/South |
ContactName | Simon Crowther |
Address | South House 300 Queensbridge |
City | London |
PostalCode | SW7 1RZ |
Country | UK |
Select a customer: Wolski Zajazd
CustomerID | WOLZA |
CompanyName | Wolski Zajazd |
ContactName | Zbyszek Piestrzeniewicz |
Address | ul. Filtrowa 68 |
City | Warszawa |
PostalCode | 01-012 |
Country | Poland |
When a user selects a customer in the dropdown list above, a function called
is executed. The function is triggered by the event:function showCustomer(str) {
var xhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getcustomer.php?q="+str, true);
xhttp.send();
}
<?php
$mysqli = new mysqli("servername", "username", "password", "dbname");
if($mysqli->connect_error) {
exit('Could not connect');
}
$sql = "SELECT customerid, companyname, contactname, address, city, postalcode, country
FROM customers WHERE customerid = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_GET['q']);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($cid, $cname, $name, $adr, $city, $pcode, $country);
$stmt->fetch();
$stmt->close();
echo "<table>";
echo "<tr>";
echo "<th>CustomerID</th>";
echo "<td>" . $cid . "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>CompanyName</th>";
echo "<td>" . $cname . "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>ContactName</th>";
echo "<td>" . $name . "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Address</th>";
echo "<td>" . $adr . "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>City</th>";
echo "<td>" . $city . "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>PostalCode</th>";
echo "<td>" . $pcode . "</td>";
echo "</tr>";
echo "<tr>";
echo "<th>Country</th>";
echo "<td>" . $country . "</td>";
echo "</tr>";
echo "</table>";
?>
Eventually the navigation links, above, will be replaced by these (previous) and (next) buttons below.
JavaScript icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon