Delete multiple selected records with jQuery and AJAX

If you are allowing the user to delete the list of records and they are more in numbers then it will hard for the user to delete the specific record one by one and consumes more time.

To make it easier you can allow multiple selections of records and delete all selected list either with the only PHP or with jQuery and AJAX.

In this tutorial, I am using jQuery AJAX to remove records.

Delete multiple selected records with jQuery and AJAX


Contents

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

1. Table structure

I am using posts table in the tutorial example.

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

2. Configuration

Create a config.php for database connection.

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. HTML

Create a delete button and display the posts table records in Table layout.

Add a checkbox in the table row and use the post id ($id) to create <tr> and checkbox element id.

Completed Code

<?php include "config.php"; ?>
<div class='container'>
 <input type='button' value='Delete' id='delete'><br><br>
 <table border='1' id='recordsTable' >
   <tr style='background: whitesmoke;'>
     <th>&nbsp;</th>
     <th>Title</th>
   </tr>

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

   $count = 1;
   while($row = mysqli_fetch_array($result) ){
     $id = $row['id'];
     $title = $row['title'];
     $link = $row['link'];
 
   ?>
     <tr id='tr_<?= $id?>'>
       <td><input type='checkbox' id='del_<?php echo $id; ?>' ></td>
       <td><a href='<?= $link; ?>'><?= $title; ?></a></td>
     </tr>
   <?php
    $count++;
  }
  ?>
 </table>
</div>

4. PHP

Create a new ajaxfile.php file.

Loop on the POST ids and execute delete query on the ids.

Completed Code

<?php 
include "config.php";
$post_ids = $_POST['post_id'];

foreach($post_ids as $id){ 
  // Delete record 
  $query = "DELETE FROM posts WHERE id=".$id; 
  mysqli_query($con,$query);
}
echo 1;

5. jQuery

On the click of delete button loop on all checked checkboxes. Get the postid by splitting the id and store in post_arr Array variable.

Check the length of the array if it greater than 0 then display confirm alert. If clicked Ok then sends an AJAX to delete the records where pass the {post_id: post_arr} as data.

On successfully callback loop on the post_arr and remove all checked rows by its ids.

Completed Code

$(document).ready(function(){

  $('#delete').click(function(){

    var post_arr = [];

    // Get checked checkboxes
    $('#recordsTable input[type=checkbox]').each(function() {
      if (jQuery(this).is(":checked")) {
        var id = this.id;
        var splitid = id.split('_');
        var postid = splitid[1];

        post_arr.push(postid);
        
      }
    });

    if(post_arr.length > 0){

        var isDelete = confirm("Do you really want to delete records?");
        if (isDelete == true) {
           // AJAX Request
           $.ajax({
              url: 'ajaxfile.php',
              type: 'POST',
              data: { post_id: post_arr},
              success: function(response){
                 $.each(post_arr, function( i,l ){
                     $("#tr_"+l).remove();
                 });
              }
           });
        } 
    } 
  });
 
});

6. Demo

Check the checkboxes and click on Delete button.


7. Conclusion

Use the checkbox element to allow multiple records selection and on delete click read checked checkboxes for deleting by sending AJAX request.

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

Leave a Comment