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 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 = [];
    $('#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){

        // AJAX Request
        $.ajax({
          url: 'remove.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

In the tutorial example, I used checkboxes to allow multiple row selection and deleting them by sending AJAX request when the delete button gets clicked.

Related Post

Spread the love

Be First to Comment

Leave a Reply

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