The most powerful use of AJAX is retrieving data directly from a **database** (like MySQL). This allows you to build single-page applications where data updates automatically based on user choices—for example, selecting a Customer Name to instantly see their order history.
JavaScript cannot talk directly to a database for security reasons. Instead, it follows this 3-step path:
In this example, we send a user's selection from a dropdown menu to a server-side file.
function showCustomer(str) {
if (str == "") {
document.getElementById("info").innerHTML = "";
return;
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("info").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getcustomer.php?id=" + str, true);
xhttp.send();
}
The PHP file connects to the database, executes a SQL query, and builds an HTML table from the results.
<?php
$mysqli = new mysqli("localhost", "user", "pass", "database");
// Search for the ID passed from AJAX
$stmt = $mysqli->prepare("SELECT name, city, balance FROM customers WHERE id = ?");
$stmt->bind_param("s", $_GET['id']);
$stmt->execute();
$result = $stmt->get_result();
// Build an HTML table to send back
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row['name'] . "</td></tr>";
}
echo "</table>";
?>