Wednesday, January 29, 2020

Ajax Pagination With Search And Product Filter In Codeigniter

Ajax Pagination With Search And Product Filter In Codeigniter

This publication is intended for Codeigniter web developers, since this publication created an elegant product filter under Codeigniter with Ajax jQuery. In this product filter, the user can filter the product details according to another filter that we created with Checkbox, and even the product can be filtered in two price ranges. To create a price range filter here, we used the sliding plug-in for the jQuery user interface. This entire operation was performed using jQuery Ajax with the Codeigniter framework.

In this Codeigniter Ajax product filter we also added the paging function. For this reason, not all product details are loaded on the same page, but rather divided into different websites. This shortens the loading time of the website. Here we used the Codeigniter paging library to add the paging functionality to the Codeigniter product filter. If the number of product loads for display on the website has increased many times, add the pagination link automatically in the Codeigniter product filter. To get from one page to the next, we also used Ajax so that the product data is loaded from another page without the website being updated. So this is the Codeigniter product filter with pagination link using Ajax.


Most e-commerce websites displayed all products with a different product filter and pagination link. The checkbox for the type of filter product data entry was also used to filter product data under various conditions. In order to filter the product data in the same way between two prices, we also used the sliding add-on for the jQuery UI library. When we have the slide price and stop it, the Ajax request is activated to receive data and display the product data on the website, which is between two prices. These are the basic functions of the Codeigniter Ajax product filter with paging function. Below is the full source code of this tutorial.


Soruce Code


Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `product`
--

CREATE TABLE `product` (
  `product_id` int(20) NOT NULL,
  `product_name` varchar(120) NOT NULL,
  `product_brand` varchar(100) NOT NULL,
  `product_price` decimal(8,2) NOT NULL,
  `product_ram` char(5) NOT NULL,
  `product_storage` varchar(50) NOT NULL,
  `product_camera` varchar(20) NOT NULL,
  `product_image` varchar(100) NOT NULL,
  `product_quantity` mediumint(5) NOT NULL,
  `product_status` enum('0','1') NOT NULL COMMENT '0-active,1-inactive'
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Dumping data for table `product`
--

INSERT INTO `product` (`product_id`, `product_name`, `product_brand`, `product_price`, `product_ram`, `product_storage`, `product_camera`, `product_image`, `product_quantity`, `product_status`) VALUES
(1, 'Honor 9 Lite (Sapphire Blue, 64 GB)  (4 GB RAM)', 'Honor', '14499.00', '4', '64', '13', 'image-1.jpeg', 10, '1'),
(2, '\r\nInfinix Hot S3 (Sandstone Black, 32 GB)  (3 GB RAM)', 'Infinix', '8999.00', '3', '32', '13', 'image-2.jpeg', 10, '1'),
(3, 'VIVO V9 Youth (Gold, 32 GB)  (4 GB RAM)', 'VIVO', '16990.00', '4', '32', '16', 'image-3.jpeg', 10, '1'),
(4, 'Moto E4 Plus (Fine Gold, 32 GB)  (3 GB RAM)', 'Moto', '11499.00', '3', '32', '8', 'image-4.jpeg', 10, '1'),
(5, 'Lenovo K8 Plus (Venom Black, 32 GB)  (3 GB RAM)', 'Lenevo', '9999.00', '3', '32', '13', 'image-5.jpg', 10, '1'),
(6, 'Samsung Galaxy On Nxt (Gold, 16 GB)  (3 GB RAM)', 'Samsung', '10990.00', '3', '16', '13', 'image-6.jpeg', 10, '1'),
(7, 'Moto C Plus (Pearl White, 16 GB)  (2 GB RAM)', 'Moto', '7799.00', '2', '16', '8', 'image-7.jpeg', 10, '1'),
(8, 'Panasonic P77 (White, 16 GB)  (1 GB RAM)', 'Panasonic', '5999.00', '1', '16', '8', 'image-8.jpeg', 10, '1'),
(9, 'OPPO F5 (Black, 64 GB)  (6 GB RAM)', 'OPPO', '19990.00', '6', '64', '16', 'image-9.jpeg', 10, '1'),
(10, 'Honor 7A (Gold, 32 GB)  (3 GB RAM)', 'Honor', '8999.00', '3', '32', '13', 'image-10.jpeg', 10, '1'),
(11, 'Asus ZenFone 5Z (Midnight Blue, 64 GB)  (6 GB RAM)', 'Asus', '29999.00', '6', '128', '12', 'image-12.jpeg', 10, '1'),
(12, 'Redmi 5A (Gold, 32 GB)  (3 GB RAM)', 'MI', '5999.00', '3', '32', '13', 'image-12.jpeg', 10, '1'),
(13, 'Intex Indie 5 (Black, 16 GB)  (2 GB RAM)', 'Intex', '4999.00', '2', '16', '8', 'image-13.jpeg', 10, '1'),
(14, 'Google Pixel 2 XL (18:9 Display, 64 GB) White', 'Google', '61990.00', '4', '64', '12', 'image-14.jpeg', 10, '1'),
(15, 'Samsung Galaxy A9', 'Samsung', '36000.00', '8', '128', '24', 'image-15.jpeg', 10, '1'),
(16, 'Lenovo A5', 'Lenovo', '5999.00', '2', '16', '13', 'image-16.jpeg', 10, '1'),
(17, 'Asus Zenfone Lite L1', 'Asus', '5999.00', '2', '16', '13', 'image-17.jpeg', 10, '1'),
(18, 'Lenovo K9', 'Lenovo', '8999.00', '3', '32', '13', 'image-18.jpeg', 10, '1'),
(19, 'Infinix Hot S3x', 'Infinix', '9999.00', '3', '32', '13', 'image-19.jpeg', 10, '1'),
(20, 'Realme 2', 'Realme', '8990.00', '4', '64', '13', 'image-20.jpeg', 10, '1'),
(21, 'Redmi Note 6 Pro', 'Redmi', '13999.00', '4', '64', '20', 'image-21.jpeg', 10, '1'),
(22, 'Realme C1', 'Realme', '7999.00', '2', '16', '15', 'image-22.jpeg', 10, '1'),
(23, 'Vivo V11', 'Vivo', '22900.00', '6', '64', '21', 'image-23.jpeg', 10, '1'),
(24, 'Oppo F9 Pro', 'Oppo', '23990.00', '6', '64', '18', 'image-24.jpg', 10, '1'),
(25, 'Honor 9N', 'Honor', '11999.00', '4', '64', '15', 'image-25.jpg', 10, '1'),
(26, 'Redmi 6A', 'Redmi', '6599.00', '2', '16', '13', 'image-26.jpeg', 10, '1'),
(27, 'InFocus Vision 3', 'InFocus', '7399.00', '2', '16', '13', 'image-27.jpeg', 10, '1'),
(28, 'Vivo Y69', 'Vivo', '11390.00', '3', '32', '16', 'image-28.jpeg', 10, '1'),
(29, 'Honor 7x', 'Honor', '12721.00', '4', '32', '18', 'image-29.jpeg', 10, '1'),
(30, 'Nokia 2.1', 'Nokia', '6580.00', '2', '1', '8', 'image-30.jpeg', 10, '1');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `product`
--
ALTER TABLE `product`
  ADD PRIMARY KEY (`product_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `product`
--
ALTER TABLE `product`
  MODIFY `product_id` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=31;


Controllers - Product_filter.php



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

class Product_filter extends CI_Controller {
 
 public function __construct()
 {
  parent::__construct();
  $this->load->model('product_filter_model');
 }

 function index()
 {
  $data['brand_data'] = $this->product_filter_model->fetch_filter_type('product_brand');
  $data['ram_data'] = $this->product_filter_model->fetch_filter_type('product_ram');
  $data['product_storage'] = $this->product_filter_model->fetch_filter_type('product_storage');
  $this->load->view('product_filter', $data);
 }

 function fetch_data()
 {
  sleep(1);
  $minimum_price = $this->input->post('minimum_price');
  $maximum_price = $this->input->post('maximum_price');
  $brand = $this->input->post('brand');
  $ram = $this->input->post('ram');
  $storage = $this->input->post('storage');
  $this->load->library('pagination');
  $config = array();
  $config['base_url'] = '#';
  $config['total_rows'] = $this->product_filter_model->count_all($minimum_price, $maximum_price, $brand, $ram, $storage);
  $config['per_page'] = 8;
  $config['uri_segment'] = 3;
  $config['use_page_numbers'] = TRUE;
  $config['full_tag_open'] = '<ul class="pagination">';
  $config['full_tag_close'] = '</ul>';
  $config['first_tag_open'] = '<li>';
  $config['first_tag_close'] = '</li>';
  $config['last_tag_open'] = '<li>';
  $config['last_tag_close'] = '</li>';
  $config['next_link'] = '&gt;';
  $config['next_tag_open'] = '<li>';
  $config['next_tag_close'] = '</li>';
  $config['prev_link'] = '&lt;';
  $config['prev_tag_open'] = '<li>';
  $config['prev_tag_close'] = '</li>';
  $config['cur_tag_open'] = "<li class='active'><a href='#'>";
  $config['cur_tag_close'] = '</a></li>';
  $config['num_tag_open'] = '<li>';
  $config['num_tag_close'] = '</li>';
  $config['num_links'] = 3;
  $this->pagination->initialize($config);
  $page = $this->uri->segment(3);
  $start = ($page - 1) * $config['per_page'];
  $output = array(
   'pagination_link'  => $this->pagination->create_links(),
   'product_list'   => $this->product_filter_model->fetch_data($config["per_page"], $start, $minimum_price, $maximum_price, $brand, $ram, $storage)
  );
  echo json_encode($output);
 }
  
}
?>


Models - Product_filter_model.php



<?php

class Product_filter_model extends CI_Model
{
 function fetch_filter_type($type)
 {
  $this->db->distinct();
  $this->db->select($type);
  $this->db->from('product');
  $this->db->where('product_status', '1');
  return $this->db->get();
 }

 function make_query($minimum_price, $maximum_price, $brand, $ram, $storage)
 {
  $query = "
  SELECT * FROM product 
  WHERE product_status = '1' 
  ";

  if(isset($minimum_price, $maximum_price) && !empty($minimum_price) &&  !empty($maximum_price))
  {
   $query .= "
    AND product_price BETWEEN '".$minimum_price."' AND '".$maximum_price."'
   ";
  }

  if(isset($brand))
  {
   $brand_filter = implode("','", $brand);
   $query .= "
    AND product_brand IN('".$brand_filter."')
   ";
  }

  if(isset($ram))
  {
   $ram_filter = implode("','", $ram);
   $query .= "
    AND product_ram IN('".$ram_filter."')
   ";
  }

  if(isset($storage))
  {
   $storage_filter = implode("','", $storage);
   $query .= "
    AND product_storage IN('".$storage_filter."')
   ";
  }
  return $query;
 }

 function count_all($minimum_price, $maximum_price, $brand, $ram, $storage)
 {
  $query = $this->make_query($minimum_price, $maximum_price, $brand, $ram, $storage);
  $data = $this->db->query($query);
  return $data->num_rows();
 }

 function fetch_data($limit, $start, $minimum_price, $maximum_price, $brand, $ram, $storage)
 {
  $query = $this->make_query($minimum_price, $maximum_price, $brand, $ram, $storage);

  $query .= ' LIMIT '.$start.', ' . $limit;

  $data = $this->db->query($query);

  $output = '';
  if($data->num_rows() > 0)
  {
   foreach($data->result_array() as $row)
   {
    $output .= '
    <div class="col-sm-4 col-lg-3 col-md-3">
     <div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px; height:450px;">
      <img src="'.base_url().'images/'. $row['product_image'] .'" alt="" class="img-responsive" >
      <p align="center"><strong><a href="#">'. $row['product_name'] .'</a></strong></p>
      <h4 style="text-align:center;" class="text-danger" >'. $row['product_price'] .'</h4>
      <p>Camera : '. $row['product_camera'].' MP<br />
      Brand : '. $row['product_brand'] .' <br />
      RAM : '. $row['product_ram'] .' GB<br />
      Storage : '. $row['product_storage'] .' GB </p>
     </div>
    </div>
    ';
   }
  }
  else
  {
   $output = '<h3>No Data Found</h3>';
  }
  return $output;
 }
}

?>


Views - product_filter.php



<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Ajax Pagination With Search And Product Filter In Codeigniter </title>

    <!-- Bootstrap Core CSS -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <link href = "<?php echo base_url(); ?>asset/jquery-ui.css" rel = "stylesheet">
    <!-- Custom CSS -->
    <link href="<?php echo base_url(); ?>asset/style.css" rel="stylesheet">
</head>

<body>
    <!-- Page Content -->
    <div class="container">
        <div class="row">
            <div class="col-md-3">
    <br />
    <br />
    <br />
    <div class="list-group">
     <h3>Price</h3>
     <input type="hidden" id="hidden_minimum_price" value="0" />
                    <input type="hidden" id="hidden_maximum_price" value="65000" />
                    <p id="price_show">1000 - 65000</p>
                    <div id="price_range"></div>
                </div>    
                <div class="list-group">
     <h3>Brand</h3>
     <?php
                    foreach($brand_data->result_array() as $row)
                    {
                    ?>
                    <div class="list-group-item checkbox">
                        <label><input type="checkbox" class="common_selector brand" value="<?php echo $row['product_brand']; ?>"  > <?php echo $row['product_brand']; ?></label>
                    </div>
                    <?php
                    }
                    ?>
                </div>

    <div class="list-group">
     <h3>RAM</h3>
     <?php
                    foreach($ram_data->result_array() as $row)
                    {
                    ?>
                    <div class="list-group-item checkbox">
                        <label><input type="checkbox" class="common_selector ram" value="<?php echo $row['product_ram']; ?>" > <?php echo $row['product_ram']; ?> GB</label>
                    </div>
                    <?php
                    }
                    ?> 
                </div>
    
    <div class="list-group">
     <h3>Internal Storage</h3>
     <?php
                    foreach($product_storage->result_array() as $row)
                    {
                    ?>
                    <div class="list-group-item checkbox">
                        <label><input type="checkbox" class="common_selector storage" value="<?php echo $row['product_storage']; ?>"  > <?php echo $row['product_storage']; ?> GB</label>
                    </div>
                    <?php
                    }
                    ?> 
                </div>
            </div>

            <div class="col-md-9">
             <h2 align="center">Product Filters in Codeigniter using Ajax</h2>
    <br />
    <div align="center" id="pagination_link">

                </div>
    <br />
    <br />
    <br />
                <div class="row filter_data">

                </div>
            </div>
        </div>

    </div>
<style>
#loading
{
 text-align:center; 
 background: url('<?php echo base_url(); ?>asset/loader.gif') no-repeat center; 
 height: 150px;
}
</style>

<script>
$(document).ready(function(){

    filter_data(1);

    function filter_data(page)
    {
        $('.filter_data').html('<div id="loading" style="" ></div>');
        var action = 'fetch_data';
        var minimum_price = $('#hidden_minimum_price').val();
        var maximum_price = $('#hidden_maximum_price').val();
        var brand = get_filter('brand');
        var ram = get_filter('ram');
        var storage = get_filter('storage');
        $.ajax({
            url:"<?php echo base_url(); ?>product_filter/fetch_data/"+page,
            method:"POST",
            dataType:"JSON",
            data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price, brand:brand, ram:ram, storage:storage},
            success:function(data)
            {
                $('.filter_data').html(data.product_list);
                $('#pagination_link').html(data.pagination_link);
            }
        })
    }

    function get_filter(class_name)
    {
        var filter = [];
        $('.'+class_name+':checked').each(function(){
            filter.push($(this).val());
        });
        return filter;
    }

    $(document).on('click', '.pagination li a', function(event){
        event.preventDefault();
        var page = $(this).data('ci-pagination-page');
        filter_data(page);
    });

    $('.common_selector').click(function(){
        filter_data(1);
    });

    $('#price_range').slider({
        range:true,
        min:1000,
        max:65000,
        values:[1000,65000],
        step:500,
        stop:function(event, ui)
        {
            $('#price_show').html(ui.values[0] + ' - ' + ui.values[1]);
            $('#hidden_minimum_price').val(ui.values[0]);
            $('#hidden_maximum_price').val(ui.values[1]);
            filter_data(1);
        }

    });

});
</script>

</body>

</html>


By Using jQuery,Ajax Bootgrid For An Crud Application In Codeigniter

By Using  jQuery,Ajax Bootgrid For  An Crud Application In Codeigniter

If you want to use Ajax to build a single page CRUD application in Codeigniter, this post is helpful. Because in this article you will learn step by step or from scratch how to use the jQuery Bootgrid plugin in Codeigniter with Ajax. The jQuery Bootgrid plug-in is a compact plug-in, a flexible and powerful grid plug-in for loading dynamic data with Ajax. It's also a very customizable grid control, especially if you've used the bootstrap library. It is mainly used to display dynamic data with Ajax.


This add-on gives you the following benefits:


  • Simple header or footer navigation
  • Table column data is saved
  • Live search or data filtering
  • pagination
  • Client-side processing and server-side data processing

First in our previous publication, in which we already dealt with processing the server-side jQuery boot grid in PHP using Ajax. But here we saw how to integrate the Bootgrid Grid plugin into the Codeigniter framework. Becase Codeigniter is the PHP MVC framework used by many web developers for their web development. If you are a Codeigniter web developer, you should know how to use the Bootgrid plugin with the Codeigniter application. For this we need to do this tutorial. In this post we will deal with Ajax after the CRUD operation with jQuery Bootgrid in Codeigniter.



  • Perform server-side processing and load data into the jQuery boot grid add-in in Codeigniter using Ajax
  • Add or insert data in MySQL in Codeigniter using Ajax with jQuery Bootgrid and Bootstrap Modal
  • Edit or update MySQL data in codeigniter using Ajax with jQuery Bootgrid and Bootstrap Modal
  • Delete or delete MySQL data in codeigniter using Ajax with jQuery Bootgrid and Bootstrap Modal




Bootgrid.php(Controller)


First we have to run Bootgrid.php Controller in the application / controller folder. This class is mainly used to process the http request to insert, update, delete and read data. In this class you will find the following function.


index () - This is the root function for this class. If we have to write the base URL with this class in the browser, this function was called. This function has bootgrid.php load view as output in the browser.


fetch_data (): This function receives the Ajax request from the boot grid plugin to get MySQL data. This function converts the data to matrix format and sends it to the Bootgrid Ajax request in JSON string format.


action () - With this function you can use ajax to insert a MySQL table or add it to the MySQL table. Because this function received an Ajax request to insert data into the mysql table.


fetch_single_data (): This function mainly looks for certain details of employees based on the value of the employee identification. You use this to edit the details of the existing employees.


delete_data (): This function is used to process the AjQ data delete request of the jQuery boot grid plug-in in Codeigniter.



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

class Bootgrid extends CI_Controller {
 
 public function __construct()
 {
  parent::__construct();
  $this->load->model('bootgrid_model');
 }

 function index()
 {
  $this->load->view('bootgrid');
 }

 function fetch_data()
 {
  $data = $this->bootgrid_model->make_query();
  $array = array();
  foreach($data as $row)
  {
   $array[] = $row;
  }
  $output = array(
   'current'  => intval($_POST["current"]),
   'rowCount'  => 10,
   'total'   => intval($this->bootgrid_model->count_all_data()),
   'rows'   => $array
  );
  echo json_encode($output);
 }

 function action()
 {
  if($this->input->post('operation'))
  {
   $data = array(
    'name'   => $this->input->post('name'),
    'address'  => $this->input->post('address'),
    'gender'  => $this->input->post('gender'),
    'designation' => $this->input->post('designation'),
    'age'   => $this->input->post('age')
   );
   if($this->input->post('operation') == 'Add')
   {
    $this->bootgrid_model->insert($data);
    echo 'Data Inserted';
   }
   if($this->input->post('operation') == 'Edit')
   {
    $this->bootgrid_model->update($data, $this->input->post('employee_id'));
    echo 'Data Updated';
   }
  }
 }

 function fetch_single_data()
 {
  if($this->input->post('id'))
  {
   $data = $this->bootgrid_model->fetch_single_data($this->input->post('id'));
   foreach($data as $row)
   {
    $output['name'] = $row['name'];
    $output['address'] = $row['address'];
    $output['gender'] = $row['gender'];
    $output['designation'] = $row['designation'];
    $output['age'] = $row['age'];
   }
   echo json_encode($output);
  }
 }

 function delete_data()
 {
  if($this->input->post('id'))
  {
   $this->bootgrid_model->delete($this->input->post('id'));
   echo 'Data Deleted';
  }
 }
}

?>


Bootgrid_model.php(Models)


We need to run this course in the application / models folder. This type of model is mainly used for all types of database operations. In this class we have the following function to perform operations related to the database.


make_query (): This function is used to search MySQL table data according to the requirements of the boot grid add-in. In this function, we performed the search for selection of search data using the where clause for searching for data, the order_by clause for sorting the data and the limit clause for paging data.


count_all_data (): This function returns the number of rows in the employee table.


insert (): Mainly used for the database insert operation. It performs the insert query, executes the query, and inserts data into the database.


fetch_single_data (): This function selects data from a single employee based on the value of the variable $ id.


update () - This function is used to update or edit the operation of the MySQL database.


delete () - This function causes mysql to delete or delete the data operation in Codeigniter.



application / models / Bootgrid_model.php

<?php
class Bootgrid_model extends CI_Model
{
 var $records_per_page = 10;
 var $start_from = 0;
 var $current_page_number = 1;

 function make_query()
 {
  if(isset($_POST["rowCount"]))
  {
   $this->records_per_page = $_POST["rowCount"];
  }
  else
  {
   $this->records_per_page = 10;
  }
  if(isset($_POST["current"]))
  {
   $this->current_page_number = $_POST["current"];
  }
  $this->start_from = ($this->current_page_number - 1) * $this->records_per_page;
  $this->db->select("*");
  $this->db->from("tbl_employee");
  if(!empty($_POST["searchPhrase"]))
  {
   $this->db->like('name', $_POST["searchPhrase"]);
   $this->db->or_like('address', $_POST["searchPhrase"]);
   $this->db->or_like('gender', $_POST["searchPhrase"]);
   $this->db->or_like('designation', $_POST["searchPhrase"]);
   $this->db->or_like('age', $_POST["searchPhrase"]);
  }
  if(isset($_POST["sort"]) && is_array($_POST["sort"]))
  {
   foreach($_POST["sort"] as $key => $value)
   {
    $this->db->order_by($key, $value);
   }
  }
  else
  {
   $this->db->order_by('id', 'DESC');
  }
  if($this->records_per_page != -1)
  {
   $this->db->limit($this->records_per_page, $this->start_from);
  }
  $query = $this->db->get();
  return $query->result_array();
 }

 function count_all_data()
 {
  $this->db->select("*");
  $this->db->from("tbl_employee");
  $query = $this->db->get();
  return $query->num_rows();
 }

 function insert($data)
 {
  $this->db->insert('tbl_employee', $data);
 }

 function fetch_single_data($id)
 {
  $this->db->where('id', $id);
  $query = $this->db->get('tbl_employee');
  return $query->result_array();
 }

 function update($data, $id)
 {
  $this->db->where('id', $id);
  $this->db->update('tbl_employee', $data);
 }

 function delete($id)
 {
  $this->db->where('id', $id);
  $this->db->delete('tbl_employee');
 }
}

?>


bootgrid.php(Views)


The file under Show Code Signiter is used to display the HTML output on the website. This view file bootgrid.php is located in the applications / views folder. Here we have created an HTML table according to the boot grid plugin, and below is the jQuery code where we initialize the jQuery boot grid plugin with the bootgrid () method. With this method, we enabled the Ajax request to get data and the Edit and Delete button under the Formatter option as well.



<html>
<head>
    <title>By Using  jQuery,Ajax Bootgrid For  An Crud Application In Codeigniter </title>
    
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-bootgrid/1.3.1/jquery.bootgrid.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-bootgrid/1.3.1/jquery.bootgrid.js"></script>  
</head>
<body>
    <div class="container box">
        <h3 align="center">By Using jQuery,Ajax Bootgrid For  An Crud Application In Codeigniter </h3><br />
        <div class="panel panel-default">
            <div class="panel-heading">
                <div class="row">
                    <div class="col-md-10">
                        <h3 class="panel-title">Employee List</h3>
                    </div>
                    <div class="col-md-2" align="right">
                        <button type="button" id="add_button" data-toggle="modal" data-target="#employeeModal" class="btn btn-info btn-xs">Add</button>
                    </div>
                </div>
                
            </div>
            <div class="panel-body">
                <div class="table-responsive">
                    <table id="employee_data" class="table table-striped table-bordered">
                        <thead>
                            <tr>
                                <th data-column-id="name">Name</th>
                                <th data-column-id="address">Address</th>
                                <th data-column-id="gender">Gender</th>
                                <th data-column-id="designation">Designation</th>
                                <th data-column-id="age">Age</th>
                                <th data-column-id="commands" data-formatter="commands" data-sortable="false">Action</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
       </div>
    </div>
</body>
</html>

<div id="employeeModal" class="modal fade">
    <div class="modal-dialog">
        <form method="post" id="employee_form">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Add Employee</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>Enter Name</label>
                        <input type="text" name="name" id="name" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Enter Address</label>
                        <textarea name="address" id="address" class="form-control"></textarea>
                    </div>
                    <div class="form-group">
                        <label>Select Gender</label>
                        <select name="gender" id="gender" class="form-control">
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Enter Designation</label>
                        <input type="text" name="designation" id="designation" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Enter Age</label>
                        <input type="text" name="age" id="age" class="form-control" />
                    </div>
                </div>
                <div class="modal-footer">
                    <input type="hidden" name="employee_id" id="employee_id" />
                    <input type="hidden" name="operation" id="operation" value="Add" />
                    <input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
                </div>
            </div>
        </form>
    </div>
</div>

<script type="text/javascript" language="javascript" >
$(document).ready(function(){
    
    var employeeTable = $('#employee_data').bootgrid({
        ajax:true,
        rowSelect: true,
        post:function()
        {
            return{
                id:"b0df282a-0d67-40e5-8558-c9e93b7befed"
            }
        },
        url:"<?php echo base_url(); ?>bootgrid/fetch_data",
        formatters:{
            "commands":function(column, row)
            {
                return "<button type='button' class='btn btn-warning btn-xs update' data-row-id='"+row.id+"'>Edit</button>" + "&nbsp; <button type='button' class='btn btn-danger btn-xs delete' data-row-id='"+row.id+"'>Delete</button>";
            }
        }
    });

    $('#add_button').click(function(){
        $('#employee_form')[0].reset();
        $('.modal-title').text("Add Employee");
        $('#action').val("Add");
        $('#operation').val("Add");
    });

    $(document).on('submit', '#employee_form', function(event){
        event.preventDefault();
        var name = $('#name').val();
        var address = $('#address').val();
        var gender = $('#gender').val();
        var designation = $('#designation').val();
        var age = $('#age').val();
        var form_data = $(this).serialize();
        if(name != '' && address != '' &&  gender != '' &&  designation != '' && age != '')
        {
            $.ajax({
                url:"<?php echo base_url(); ?>bootgrid/action",
                method:"POST",
                data:form_data,
                success:function(data)
                {
                    alert(data);
                    $('#employee_form')[0].reset();
                    $('#employeeModal').modal('hide');
                    $('#employee_data').bootgrid('reload');
                }
            });
        }
        else
        {
            alert("All Fields are Required");
        }
    });

    $(document).on("loaded.rs.jquery.bootgrid", function(){
        employeeTable.find('.update').on('click', function(event){
            var id = $(this).data('row-id');
            $.ajax({
                url:"<?php echo base_url(); ?>bootgrid/fetch_single_data",
                method:"POST",
                data:{id:id},
                dataType:"json",
                success:function(data)
                {
                    $('#employeeModal').modal('show');
                    $('#name').val(data.name);
                    $('#address').val(data.address);
                    $('#gender').val(data.gender);
                    $('#designation').val(data.designation);
                    $('#age').val(data.age);
                    $('.modal-title').text("Edit Employee Details");
                    $('#employee_id').val(id);
                    $('#action').val('Edit');
                    $('#operation').val('Edit');
                }
            });
        });

        employeeTable.find('.delete').on('click', function(event){
            if(confirm("Are you sure you want to delete this?"))
            {
                var id = $(this).data('row-id');
                $.ajax({
                    url:"<?php echo base_url(); ?>bootgrid/delete_data",
                    method:"POST",
                    data:{id:id},
                    success:function(data)
                    {
                        alert(data);
                        $('#employee_data').bootgrid('reload');
                    }
                });
            }
            else
            {
                return false;
            }
        });
    });
    
});
</script>



With the help of this publication, you create the one-sided application Codeigniter Ajax with the plugin jQuery Bootgrid.