Delete Multiple selected Records with jQuery AJAX in CodeIgniter 3

One by One record deletion from the list is time-consuming and frustrating when you need to delete many records.

With the use of the checkboxes on the list, you can allow selecting multiple records. Only required to add a single delete button.

In this tutorial, I show how you can delete multiple records using jQuery AJAX in CodeIgniter.

Delete multiple selected records with jQuery AJAX in CodeIgniter 3

 


Contents

  1. Table structure
  2. Configuration
  3. Model
  4. Controller
  5. View
  6. Demo
  7. Conclusion

1. Table structure

In this example, I am using users table and added some records –

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `email` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. Configuration

Navigate to application/config/database.php and define the Database connection.

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root', // Username
 'password' => '', // Password
 'database' => 'tutorial', // Database name
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);

Default controller

Open application/config/routes.php and edit default_controller value to Users.

$route['default_controller'] = 'Users';

Load Database

To access the MySQL database require loading database library.

Open application/config/autoload.php and add the database in libraries array().

$autoload['libraries'] = array("database");

3. Model

Create a Main_model.php file in application/models/ directory.

Here, create 3 methods –

  • __construct()
  • getUsers() – Fetch all records from users table and return it.
  • deleteUser() – Loop on $user_ids Array and execute Delete query on id.

Completed Code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

Class Main_model extends CI_Model {

   public function __construct() { 
      parent::__construct(); 
   }

   // Fetch records
   public function getUsers() {

     // Users
     $this->db->select('*');
     $this->db->from('users');
     $this->db->order_by("id", "asc");
     $usersquery = $this->db->get();

     $usersResult = $usersquery->result_array();

     return $usersResult;
   }

   // Delete record
   public function deleteUser($user_ids = array() ){

      foreach($user_ids as $userid){
         $this->db->delete('users', array('id' => $userid));
      }

      return 1;
   }

}

4. Controller

Create a Users.php file in application/controllers/ directory.

Here, create 3 methods –

  • __construct() – Load url helper and Main_model Model.
  • index() – Get all users list by calling getUsers() method and assign in $data Array. Load index_view and also pass $data.
  • deleteUser() – This method uses to handle AJAX request and return response.

Read POST values and call Main_model deleteUser() method to delete records where pass POST value as a parameter.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Users extends CI_Controller {

   public function __construct(){

      parent::__construct();
      $this->load->helper('url');

      // Load model
      $this->load->model('Main_model');

   }

   public function index(){

      $data = array();

      // Fetch all records
      $data['users'] = $this->Main_model->getUsers();

      // Load view
      $this->load->view('index_view',$data);
   }

   // Update rating
   public function deleteUser(){

      // POST values
      $user_ids = $this->input->post('user_ids');

      // Delete records
      $this->Main_model->deleteUser($user_ids);

      echo 1;
      exit;
   }

}

5. View

Create index_view.php file in application/views/ directory.

Create a <table> to list users list.

In the header row added 4 cells. To check uncheck all checkboxes added Check All checkbox and a delete button on the last cell.

Loop on $users to create <tr>. In the <tr> added id attribute to remove it when record deleted successfully using jQuery AJAX.

Add checkbox to record selection for delete. Pass $id in the value attribute.


Script

  • Check All checkbox –

When checking all checkbox state change then check if it is checked or not.

If checked then set checked all checkboxes otherwise unchecked.

  • Checkbox clicked –

When any checkbox gets clicked then check if total checkboxes is equal to total checked checkboxes.

If it is equal then set checkall checkbox checked otherwise unchecked.

  • Delete button clicked –

On Delete button click popup confirm alert. If OK button clicked then loop on all checked checkboxes and assign the value in users_arr Array.

If users_arr Array length is greater than 0 then send AJAX POST request to ‘<?= base_url() ?>index.php/users/deleteUser’.

Pass users_arr as data.

On successful callback again loop on all checked checkboxes to remove <tr>.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <title>Delete Multiple selected Records with jQuery AJAX in CodeIgniter 3</title>

      <!-- jQuery library -->
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   </head>
   <body>

      <!-- User List -->
     <table border='1' width='100%'>
        <thead>
          <th>Username</th> 
          <th>Name</th>
          <th>Email</th>
          <th><input type="checkbox" id="checkall" value='1'>&nbsp;
             <input type="button" id="delete" value='Delete'></th>
        </thead>

        <tbody>
        <?php 
        foreach($users as $user){
           $id = $user['id'];
           $username = $user['username'];
           $name = $user['name'];
           $email = $user['email'];
        ?>
           <tr id='tr_<?= $id ?>'>
              <td><?= $username ?></td>
              <td><?= $name ?></td>
              <td><?= $email ?></td>
              <td align='center'><input type="checkbox" class='checkbox' name='delete' value='<?= $id ?>' ></td>
           </tr>
        <?php
        }
        ?>
        </tbody>
     </table>

     <!-- Script -->
     <script type="text/javascript">
     $(document).ready(function(){

        // Check all
        $("#checkall").change(function(){

           var checked = $(this).is(':checked');
           if(checked){
              $(".checkbox").each(function(){
                  $(this).prop("checked",true);
              });
           }else{
              $(".checkbox").each(function(){
                  $(this).prop("checked",false);
              });
           }
        });

        // Changing state of CheckAll checkbox 
        $(".checkbox").click(function(){

           if($(".checkbox").length == $(".checkbox:checked").length) {
               $("#checkall").prop("checked", true);
           } else {
               $("#checkall").prop("checked",false);
           }

        });

        // Delete button clicked
        $('#delete').click(function(){

           // Confirm alert
           var deleteConfirm = confirm("Are you sure?");
           if (deleteConfirm == true) {

              // Get userid from checked checkboxes
              var users_arr = [];
              $(".checkbox:checked").each(function(){
                  var userid = $(this).val();

                  users_arr.push(userid);
              });

              // Array length
              var length = users_arr.length;

              if(length > 0){

                 // AJAX request
                 $.ajax({
                    url: '<?= base_url() ?>index.php/users/deleteUser',
                    type: 'post',
                    data: {user_ids: users_arr},
                    success: function(response){

                       // Remove <tr>
                       $(".checkbox:checked").each(function(){
                           var userid = $(this).val();

                           $('#tr_'+userid).remove();
                       });
                    }
                 });
              }
           } 

        });

      });
      </script>

   </body>
</html>

6. Demo

View Demo


7. Conclusion

Assign the delete id in the checkbox value attribute. On Delete button click read the checked checkboxes value and pass in the AJAX request for delete.

It is always better to popup a confirmation alert before deleting the record. The user can cancel it if the Delete button is clicked mistakenly.

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