The finest example using ajax, PHP, and MySQL is what I’ve presented. Therefore, you can learn how to delete data using Ajax in PHP and MySQL. Simple explanations are provided for each stage.
- Create an AJAX request to the PHP script.
- In the PHP script, receive the data from the AJAX request.
- Connect to the database using PHP’s MySQLi or PDO extension.
- Write a DELETE SQL query to delete the data based on the received data.
- Execute the query using the query method of the database connection object.
- Return a success or error response to the AJAX request.
- Handle the response in the success callback of the AJAX request.
- Here is an example code for reference:
jQuery.ajax({ type: "POST", url: "delete.php", data: { id: id }, success: function(data) { if(data == "success") { // show success message } else { // show error message } } });
2. delete.php
<?php $servername='localhost'; $username='root'; $password=''; $dbname = "database"; $conn = mysqli_connect($servername,$username,$password,$dbname); // Create connection if (!$conn) { die("Unable to Connect database: " . mysqli_connect_error()); } $id = $_REQUEST['id']; $sql = "DELETE FROM users WHERE id=$id"; if (mysqli_query($conn, $sql)) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . mysqli_error($conn); } mysqli_close($conn); ?>