How To Delete Data From Database Using Ajax In PHP

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.

  1. Create an AJAX request to the PHP script.
  2. In the PHP script, receive the data from the AJAX request.
  3. Connect to the database using PHP’s MySQLi or PDO extension.
  4. Write a DELETE SQL query to delete the data based on the received data.
  5. Execute the query using the query method of the database connection object.
  6. Return a success or error response to the AJAX request.
  7. Handle the response in the success callback of the AJAX request.

 

  1. 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); 
?>

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories