AJAX (Asynchronous JavaScript and XML) allows us to send requests to the server and receive data without refreshing the page. This tutorial demonstrates how to delete records from a MySQL database using AJAX and PHP for a smooth user experience.
A list of records is loaded from the database. When a user clicks the delete button, an AJAX request is sent to PHP, the record is removed from the database, and the row is deleted from the page without refresh.
// Display table and handle AJAX delete
<table id="recordsTable">
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</table>
<script>
function deleteRecord(id) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "delete.php?id=" + id, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var row = document.getElementById("row_" + id);
row.parentNode.removeChild(row);
}
};
xhr.send();
}
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
<?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 id='row_{$row['id']}'>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
<td>{$row['email']}</td>
<td><button onclick='deleteRecord({$row['id']})'>Delete</button></td>
</tr>";
}
$conn->close();
?>
// Delete record by ID
<?php
$conn = new mysqli("localhost","username","password","database");
if ($conn->connect_error) {
die("Connection failed");
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$conn->query("DELETE FROM users WHERE id=$id");
}
$conn->close();
?>
When a record is deleted, the corresponding table row disappears instantly without refreshing the page.