One of the most powerful uses of AJAX is communicating with a database without reloading the page. This is heavily used in admin dashboards, live data filtering, and dynamic content loading.
JavaScript cannot connect to a MySQL database directly for security reasons. Instead, JavaScript asks PHP to talk to the database for it!
Imagine a dropdown menu containing a list of user IDs. When you select an ID, the page instantly displays that specific user's details fetched from a database.
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
</select>
</form>
<div id="txtHint"><b>User info will be listed here...</b></div>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
// Send the selected ID to the PHP script
xmlhttp.open("GET", "getuser.php?q=" + str, true);
xmlhttp.send();
}
</script>
getuser.php)When the dropdown selection changes, getuser.php receives the request. It connects to the MySQL database, fetches the requested record, and formats the output as an HTML table.
<?php $q = intval($_GET['q']);$con = mysqli_connect('localhost', 'username', 'password', 'my_db'); if (!$con) { die('Could not connect: ' . mysqli_error($con)); }
$sql = "SELECT * FROM Users WHERE id = '" . $q . "'"; $result = mysqli_query($con, $sql);
echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr>";
while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['FirstName'] . "</td>"; echo "<td>" . $row['LastName'] . "</td>"; echo "<td>" . $row['Age'] . "</td>"; echo "</tr>"; } echo "</table>";
mysqli_close($con); ?>
The JavaScript receives this generated HTML table as this.responseText and injects it directly into the <div id="txtHint"> container!
Why can't JavaScript connect directly to the MySQL database?