AJAX allows updating database records dynamically without refreshing the page. This technique improves user experience by enabling seamless communication between client-side scripts and the server.
The browser sends asynchronous requests to the server using JavaScript. PHP processes the request, updates the database, and returns a response that updates the page without reload.
// Load records and send update request using AJAX
<table id="recordsTable">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</table>
<script>
function updateRecord(id) {
var name = document.getElementById("name_" + id).value;
var email = document.getElementById("email_" + id).value;
var xhr = new XMLHttpRequest();
xhr.open("POST", "update.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("response").innerHTML = xhr.responseText;
}
};
xhr.send("id=" + id + "&name=" + name + "&email=" + email);
}
function loadRecords() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "fetch_records.php", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("recordsTable").innerHTML += xhr.responseText;
}
};
xhr.send();
}
window.onload = loadRecords;
</script>
// Fetch records from database and generate editable rows
<?php
$conn = new mysqli("localhost", "username", "password", "database");
if ($conn->connect_error) {
die("Connection failed");
}
$result = $conn->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo "<tr>
<td>{$row['id']}</td>
<td><input id='name_{$row['id']}' value='{$row['name']}'></td>
<td><input id='email_{$row['id']}' value='{$row['email']}'></td>
<td><button onclick='updateRecord({$row['id']})'>Update</button></td>
</tr>";
}
$conn->close();
?>
// Update user record securely using POST data
<?php
$conn = new mysqli("localhost", "username", "password", "database");
if ($conn->connect_error) {
die("Connection failed");
}
$id = $_POST["id"];
$name = mysqli_real_escape_string($conn, $_POST["name"]);
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$sql = "UPDATE users SET name='$name', email='$email' WHERE id=$id";
echo $conn->query($sql) ? "Record updated successfully" : "Update failed";
$conn->close();
?>
When the Update button is clicked, the record is updated instantly in the database without reloading the page.