Sunday, 2 December 2018

Ajax Codeigniter Product Filter with Pagination

Ajax Codeigniter Product Filter with Pagination - Part 1



Ajax Codeigniter Product Filter with Pagination - Part 2



Ajax Codeigniter Product Filter with Pagination - Part 3



Ajax Codeigniter Product Filter with Pagination - Part 4




This post is for Codeigniter web developer, because in this post we have make stylish product filter in Codeigniter framework by using Ajax jQuery. In this product filter user can filter product details by different filter which we have make by using Checkbox, and even product can be filter on two price range. For make price range filter here we have use jQuery UI slider plugin. This all operation has been done by using jQuery Ajax with Codeigniter framework.

In this Codeigniter ajax product filter we have also add pagination feature also. So, all product details will not be load on same page but it will be divided into different web page. So, it will reduce web page loading time. Here we have use Codeigniter pagination library for add pagination feature into Codeigniter product filter. If number of product load has been increase by limit to display on webpage, then in Codeigniter product filter it will automatically add pagination link. For go to one page to another page, here also we have use ajax also, so it will load another page product data without refresh of web page. So, this is Codeigniter product filter with pagination link using Ajax.


In most of the ecommerce website all product has been display with differnt product filter with pagination link. There are also for filter product data input type checkbox has been used for filter product data on different condition. Sameway for filter product data between two price, for this here also we have use jQuery UI library slider plugin. When we have slide price, and stop slide then it will fire ajax request for fetch data and display product data on web page which come between two price. These are basic functionality of Codeigniter Ajax Product filter with pagination feature. Below you can find complete 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>Product Filters in Codeigniter using Ajax</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>

59 comments:

  1. $brand = $this->input->post('brand'); i can't find this input !!

    ReplyDelete
    Replies
    1. if your are facing any issue please send the email i will send zip file.

      Delete
    2. Hello friend, can you send me the zip file? I'm having difficulties

      my email: eublostudio@gmail.com

      Delete
  2. can we do this one using core php with ajax?

    ReplyDelete
  3. Just wanted to hint that MariaDB and MySQL suggest InnoDB tables

    "InnoDB is a more robust and better database table type for modern applications like MODX Revolution compared to the older MyISAM table type. With InnoDB, you should see improvements in platform I/O, your sites should perform better and faster, and they should better survive database hiccups that can occur, too."

    ReplyDelete
  4. Kindly, since some of us is Codeigniter and PHP student,

    usually we are on localhost with XAMPP or WAMP or similar

    so, do you have one post on how to setup the codeigniter configuration files

    mean a Codeigniter for XAMPP/WAMP setup guide that will allow to follow the various tutorials that you publish

    thank you

    ReplyDelete
  5. Since you have images ... this tutorial really needs a Download Source code :-)

    ReplyDelete
  6. HELPPPP, Can I download this soucre code?
    POST http://localhost/code/Product_filter/fetch_data/1 404 (Not Found)

    ReplyDelete
  7. Hello
    Please share the full source code for download

    ReplyDelete
  8. Hello
    Please share the full source code for download

    ReplyDelete
  9. Hello
    Please share the full source code for download

    ReplyDelete
  10. please provide download link

    ReplyDelete
  11. we are not know what is the resign base url is not working

    ReplyDelete
  12. how to shortby product price selec options?
    (js)

    ReplyDelete
  13. model function make_query order by ASC DESC

    ReplyDelete
  14. please create this tutorial in laravel

    ReplyDelete
  15. var brand = get_filter('brand');
    var ram = get_filter('ram');
    var storage = get_filter('storage');

    can't pass these array value to php with ajax

    ReplyDelete
  16. When i want to add a dropdownbox in the view section, instead of checkbox, how can that be done?

    ReplyDelete
  17. please share download link of source code.....

    ReplyDelete
  18. please content script of config/routes.php ??

    ReplyDelete
  19. Hi, can you please send me the zip file of the source code? Email: dianhgrove@gmail.com

    ReplyDelete
    Replies
    1. Hi, we have recently add source code download link under this post, so check it.

      Delete
  20. please help, I can't get the products to display on the page??

    ReplyDelete
  21. Hi,can you please send me the zip file of the source code?...Thank you.

    ReplyDelete
  22. why are you using the isset() aging in the model i think ci input method takes care of that

    ReplyDelete
  23. i have done the advanced product filter but cant place the pagination.so please advice me how i can update the script...

    ReplyDelete
  24. I want the entire zip file pls

    ReplyDelete
  25. help me. please send me the zip file of the source code?...Thank you.

    ReplyDelete
  26. hi sir. My error is -->undefined variable: brand_data line 44 how would I fix it? I want the entire zip file too.

    ReplyDelete
  27. Awesome tutorial. Cleared my many doubts. Thank you so much. keep it up.

    ReplyDelete

  28. Hi, could you send me a zip file with the source code? ... Thank you.

    ReplyDelete
  29. Great tutorial! Could you send me the source zip file? Thanks!

    ReplyDelete
  30. Hello, please send the complete code

    ReplyDelete
    Replies
    1. Hi, we have recently add source code download link under this post, so check it.

      Delete
  31. Send the zip file to my email? eublostudio@gmail.com thanks

    ReplyDelete
    Replies
    1. Hi, we have recently add source code download link under this post, so check it.

      Delete
  32. please sent me zip file,,,,fr.5307020@gmail.com

    ReplyDelete
    Replies
    1. Hi, we have recently add source code download link under this post, so check it.

      Delete
  33. Replies
    1. Hi, we have recently add source code download link under this post, so check it.

      Delete
  34. Hi This is an excellent tutorial, i will be implementing this into my projects as this is the easiest tutorial to follow that I have found so far.

    Thanks
    bespokedesignblog.co.uk

    ReplyDelete
  35. Hii

    Can you create a similar project in Java? I need it very much for my project. Please make it soon.
    my email:ajaysinghrajput352@gmail.com

    ReplyDelete
  36. function get_filter(class_name) is note work properly null value send by class
    please solve it .immediately

    ReplyDelete
  37. When you click at pagination (current active page no), it will have error (undefined)

    ReplyDelete