Confirmation alert Before Delete record with jQuery AJAX

It is safe to display a confirmation alert before deleting a record from the MySQL database table.

If the user has accidentally clicked the delete button on the wrong record then it has a choice whether to delete or cancel it.

Confirm box can easily add using confirm() method.

But in this tutorial, I am using the Bootstrap Bootbox.js library to display the confirm box.

With jQuery AJAX delete a record from the MySQL database with PHP on the confirmation.

Confirmation alert Before Delete record with jQuery AJAX


Contents

  1. Table structure
  2. Configuration
  3. Download & Include
  4. HTML & PHP
  5. PHP
  6. jQuery
  7. Demo
  8. Conclusion

1. Table structure

I am using posts table in the example and added some records.

CREATE TABLE `posts` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `title` varchar(200) NOT NULL,
  `content` text NOT NULL,
  `link` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a config.php file for the database configuration.

Completed Code

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

3. Download & Include

  • Download Bootbox.js from here.
  • Include with Bootstrap and jQuery library.
<link href='bootstrap/css/bootstrap.min.css' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='bootstrap/js/bootstrap.min.js'></script> 
<script src='bootbox.min.js'></script>

4. HTML & PHP

Fetch records from posts table and list in the <table>.

Add a delete button <button class='delete'> on each row where use the $id to set id attribute value del_<?= $id ?>.

Completed Code

<?php 
include "config.php";
?>
<div class='container'>
  <table border='1' class='table'>
    <tr style='background: whitesmoke;'>
      <th>S.no</th>
      <th>Title</th>
      <th>Operation</th>
    </tr>

    <?php 
    $query = "SELECT * FROM posts";
    $result = mysqli_query($con,$query);

    $count = 1;
    while($row = mysqli_fetch_assoc($result) ){
       $id = $row['id'];
       $title = $row['title'];
       $link = $row['link'];

    ?>
    <tr>
       <td align='center'><?= $count ?></td>
       <td><a href='<?= $link ?>' target='_blank'><?= $title ?></a></td>
       <td align='center'>
        <button class='delete btn btn-danger' id='del_<?= $id ?>' data-id='<?= $id ?>' >Delete</button>
       </td>
    </tr>
    <?php
      $count++;
    }
    ?>
  </table>
</div>

5. PHP

Create a new ajaxfile.php file.

Check if 'id' is POST or not. If POST then prepares DELETE query to delete a record from posts table by id and return 1.

If 'id' is not POST then return 0.

Completed Code

<?php 
include "config.php";

if(isset($_POST['id'])){
   $id=  $_POST['id'];

   $sql = "DELETE FROM posts WHERE id=".$id;
   mysqli_query($con,$sql);
   echo 1;
   exit;
}

echo 0;
exit;

6. jQuery

On the button click assign this to el variable and get delete id from data-id attribute..

Show confirmation box by calling bootbox.confirm() method.

If clicked on the OK button then send an AJAX to delete a record.

On successful callback if response == 1 then remove <tr>.from <table > otherwise display alert message using bootbox.alert().

Completed Code

$(document).ready(function(){

  // Delete 
  $('.delete').click(function(){
      var el = this;
  
      // Delete id
      var deleteid = $(this).data('id');
 
      // Confirm box
      bootbox.confirm("Do you really want to delete record?", function(result) {
 
         if(result){
            // AJAX Request
            $.ajax({
                url: 'ajaxfile.php',
                type: 'POST',
                data: { id:deleteid },
                success: function(response){

                   // Removing row from HTML Table
                   if(response == 1){
		       $(el).closest('tr').css('background','tomato');
                       $(el).closest('tr').fadeOut(800,function(){
		           $(this).remove();
		       });
	           }else{
		       bootbox.alert('Record not deleted.');
	           }

                }
            });
         }
 
      });
 
  });
});

7. Demo

View Demo


8. Conclusion

If you are not using Bootstrap on your webpage then use confirm() method. Send your AJAX request to delete the record when confirm() method returns true.

If you found this tutorial helpful then don't forget to share.