This topic explains how to delete records from a MySQL database using PHP while triggering the request from JavaScript using the Fetch API.
The fetch() method sends asynchronous HTTP requests. When deleting data, it usually uses POST or DELETE methods and sends JSON data to a PHP script.
// JavaScript function sending delete request using Fetch API
function deleteUser(id) {
fetch("delete.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: id })
})
.then(response => response.text())
.then(data => console.log(data));
}
// Example usage
deleteUser(2);
// PHP script to receive JSON data and delete a record
$conn = new mysqli("localhost","root","","testdb");
$data = json_decode(file_get_contents("php://input"), true);
$id = $data['id'];
$sql = "DELETE FROM users WHERE id=$id";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record";
}
$conn->close();
When the delete function runs, a network request is sent to delete.php. If successful, the server responds with a confirmation message.
Imagine a table with a delete button beside each user. Clicking the button triggers the JavaScript function, removing the record without reloading the page.
Create a dynamic user list with delete buttons and remove users instantly using Fetch API.