Friday, 10 August 2018

How to Make Product Filter in php using Ajax



Most of the e-commerce websites provide nice UI for filter product on their website by using different type of search filter like price range product filter and checkbox search filter. This type of product search filter with price range filter and checkbox product filter feature we have discuss here by using Ajax with PHP. In this post we will describe you how to search a product from list of product by using Ajax JQuery PHP and Mysql. Here we have developed product filter which are similar to largest e-commerce website. They have use this type of search filter for filter product on their website, so user can easily filter product on different category search filter. If user has select any price range then in this feature it will filter product which has been covered between that price range and same way if user want to find particular brand product which has come between that price range then user can also select brand then it will live display all product which relate to particular brand.

This tutorial is based on live filter of product using Ajax which has been used most of the ecommerce website. If you have visit any ecommerce website for buying product then you have first prefer price and in that price we want to get particular brand then you have to find particular product then you can easily filter from list of product on web page without refresh of web page. Here we have get result by using Ajax Jquery with PHP and Mysql. For make this type of functionality for our web application we have use Jquery UI slider plugin for filter product on price and HTML Checkbox input field for filter product on different category like brand etc. If user select particular condition and that condition will match with data available in database then that product will be display using PHP with Ajax. And if user clear filter then it will seen all product on web page. Below you can find complete source code of Ajax PHP Product filter.












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');

--
-- 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=15;


database_connection.php



<?php 

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

?>


index.php



<?php 

//index.php

include('database_connection.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 filter in php</title>

    <script src="js/jquery-1.10.2.min.js"></script>
    <script src="js/jquery-ui.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link href = "css/jquery-ui.css" rel = "stylesheet">
    <!-- Custom CSS -->
    <link href="css/style.css" rel="stylesheet">
</head>

<body>
    <!-- Page Content -->
    <div class="container">
        <div class="row">
         <br />
         <h2 align="center">Advance Ajax Product Filters in PHP</h2>
         <br />
            <div class="col-md-3">                    
    <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>
                    <div style="height: 180px; overflow-y: auto; overflow-x: hidden;">
     <?php

                    $query = "SELECT DISTINCT(product_brand) FROM product WHERE product_status = '1' ORDER BY product_id DESC";
                    $statement = $connect->prepare($query);
                    $statement->execute();
                    $result = $statement->fetchAll();
                    foreach($result 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>

    <div class="list-group">
     <h3>RAM</h3>
                    <?php

                    $query = "
                    SELECT DISTINCT(product_ram) FROM product WHERE product_status = '1' ORDER BY product_ram DESC
                    ";
                    $statement = $connect->prepare($query);
                    $statement->execute();
                    $result = $statement->fetchAll();
                    foreach($result 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
                    $query = "
                    SELECT DISTINCT(product_storage) FROM product WHERE product_status = '1' ORDER BY product_storage DESC
                    ";
                    $statement = $connect->prepare($query);
                    $statement->execute();
                    $result = $statement->fetchAll();
                    foreach($result 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">
             <br />
                <div class="row filter_data">

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

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

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

    filter_data();

    function filter_data()
    {
        $('.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:"fetch_data.php",
            method:"POST",
            data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price, brand:brand, ram:ram, storage:storage},
            success:function(data){
                $('.filter_data').html(data);
            }
        });
    }

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

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

    $('#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();
        }
    });

});
</script>

</body>

</html>


fetch_data.php



<?php

//fetch_data.php

include('database_connection.php');

if(isset($_POST["action"]))
{
 $query = "
  SELECT * FROM product WHERE product_status = '1'
 ";
 if(isset($_POST["minimum_price"], $_POST["maximum_price"]) && !empty($_POST["minimum_price"]) && !empty($_POST["maximum_price"]))
 {
  $query .= "
   AND product_price BETWEEN '".$_POST["minimum_price"]."' AND '".$_POST["maximum_price"]."'
  ";
 }
 if(isset($_POST["brand"]))
 {
  $brand_filter = implode("','", $_POST["brand"]);
  $query .= "
   AND product_brand IN('".$brand_filter."')
  ";
 }
 if(isset($_POST["ram"]))
 {
  $ram_filter = implode("','", $_POST["ram"]);
  $query .= "
   AND product_ram IN('".$ram_filter."')
  ";
 }
 if(isset($_POST["storage"]))
 {
  $storage_filter = implode("','", $_POST["storage"]);
  $query .= "
   AND product_storage IN('".$storage_filter."')
  ";
 }

 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $total_row = $statement->rowCount();
 $output = '';
 if($total_row > 0)
 {
  foreach($result 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="image/'. $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>';
 }
 echo $output;
}

?>







77 comments:

  1. Great Bossssssssssssssssssssssssssssssss!!

    ReplyDelete
  2. how to use Pagination in this ?

    ReplyDelete
  3. Replies
    1. thank you so much!
      I got a problem here, can you help me?
      i need to retrieve image and its description from mysql database using php and bootstrap

      Delete
  4. It does not have database. Where is the sql file?

    ReplyDelete
  5. How can I put a select option with products name? obrigado

    ReplyDelete
  6. Je suis vraiment content, parceque j'ai beaucoup appris à votre côté. Merci proffeseur .

    ReplyDelete
  7. s'il vous plaît, vous pouvez créer le droit d'accessoires aux pages ?
    Vraiment ça sera très super. Merci .

    ReplyDelete
  8. please add pagination on this video ?

    ReplyDelete
  9. Hello can you please make the checkbox into dropdown please?? I am trying to make a product filter just like this but the checkbox is in dropdown

    ReplyDelete
  10. how to use Pagination in this ?

    ReplyDelete
  11. Hello Sir, The download link is corrupted now .Can you please re upload the link . it will be usefull to us

    ReplyDelete
  12. wow!!! this is awesome
    but am having some issues. it seems the js disables some other js codes in my php script.

    ReplyDelete
    Replies
    1. you have to add css at after title of page and js links are above of close of body tag...

      Delete
  13. how to use Pagination in this ?

    ReplyDelete
  14. hey i don't see any SQL injection protection.. what is the best way to fix it.. i different ways.. an example used prepared statements. But what is the best way.

    Great script btw :)

    ReplyDelete
  15. great tutorial bos.. but please update your code and add pagination , filter data and search please.. i have been try make pagination with ajax but not working very well.

    ReplyDelete
  16. por favor agregar pagination sin codeigniter, solo a este proyecto

    ReplyDelete
  17. how can i make the product filter like this?
    https://www.abenson.com/computers-gadget/notebook.html

    ReplyDelete
  18. Anybody help me? If in some Brand for example Nokia category of Ram only = Ram 2 GB, how to hide other rows from filter?

    ReplyDelete
  19. Dears,
    I downloaded the source code "advance-ajax-php-product-search-filter.rar"
    and I tried to UnRAR with the offered LINK, but I received an error message:
    "abort(-1) at Error at jsStackTrace (http://iblogbox.github.io/js/rar/libunrar.js:1:21152) at stackTrace "

    I tried also with Total Commander but it seams to be the RAR file is bad.

    Could any body hel me?

    Thank you
    Laszlo

    ReplyDelete
  20. Hello, thank you for your tutorial. It is absolutly super easy to use :-) But I have only one problem. I need to share filtering result. Is this possible to add function, that enabe deep linking?

    Thank you verz much
    Ivan

    ReplyDelete
  21. After adding order by DESC,products showing in DESC ORDER but filters not working.


    ReplyDelete
  22. PERFECT u r BEST !!!
    can u do this with paging?
    thanks

    ReplyDelete
  23. please, add pagination in the script

    ReplyDelete
  24. Good morning Sir. All your videos or tutorials helped me a lot today i matters me a lot to thank you.

    ReplyDelete
  25. Hello, it's working, I have a problem with the brands. they are not displayed on the page when I run this code. Is there a bug in the code? can you check it? please

    ReplyDelete
  26. sir if ( SELECT * FROM product WHERE product_status = '1' order by product_id desc )
    then out put is no product No Data Found
    plese send me solution -> vermaguru460@gmail.com

    ReplyDelete
  27. thank you very much. Hoe then do you integrate pagination

    ReplyDelete
  28. Great!!! Kindly add pagination to this. Thanks man.

    ReplyDelete
  29. How to add addtocart button and cart page

    ReplyDelete
  30. How to add add-to-cart functionality in this?

    ReplyDelete
  31. Here how can i add add to cart function?

    ReplyDelete
  32. Awesome Yaar Too Good and It helps me a Lot..
    Keep Sharing
    Thanks

    ReplyDelete
  33. How to pagination, please do help

    ReplyDelete
  34. Sir please tell me how to add input field search in this product filter script

    ReplyDelete
  35. This is great. But can you have this on wordpress?

    ReplyDelete
  36. You guys are the best. I have improved since i started following you guys. keep it up

    ReplyDelete
  37. $query = "
    SELECT * FROM product WHERE product_status = '1' ORDER BY id DESC
    ";

    Filter Not working after clicking any product. please provide solution.

    ReplyDelete
  38. Fatal error: Uncaught Error: Call to a member function prepare() on null in D:\xampp\htdocs\advance-ajax-php-product-search-filter\index.php:53 Stack trace: #0 {main} thrown in



    i got this error please reply

    ReplyDelete
  39. How to add pagination to this one ?

    ReplyDelete
  40. Thank you so much. You have solved my problem.

    ReplyDelete
  41. The most interesting thing would be... how change the filter values depending on the checkbox events? If you select 8GB RAM then change the brands only to Samsung! If this is possible, then it is perfect and can be really used!

    ReplyDelete
  42. Hello, thanks for that tutorial. Please tell me how I can add parameters to url?

    ReplyDelete
  43. Thanks for that tutorial. Please tell me how I can add parameters to url?

    ReplyDelete
  44. Fatal error
    : Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'AND nombreentreprise IN('1 - 10')' at line 3 in /Applications/XAMPP/xamppfiles/htdocs/job/fetch_data.php:26 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/job/fetch_data.php(26): PDOStatement->execute() #1 {main} thrown in
    /Applications/XAMPP/xamppfiles/htdocs/job/fetch_data.php
    on line
    26

    ReplyDelete
  45. code is not working.. pls help

    ReplyDelete
  46. Thanks. And your download archive is corrupted

    ReplyDelete
  47. Thanks. And your download archive is corrupted

    ReplyDelete
  48. Hello Sir, can you guide me how to place my href value (like this code href="../product.php?j=") from javascript ajax function in index.php that will show only my selected value from fetch_data.

    ReplyDelete
  49. Thank you so much but i need data insertion php code

    ReplyDelete
  50. sir can u give me files, because download link is corrupted

    ReplyDelete
  51. download link is corrupted.. can please share some other link for this codes

    ReplyDelete
  52. great demo! thank you!
    is possible to add a delete filter button to erase all filters?

    ReplyDelete
  53. Hello Sir, The download link is corrupted now .Can you please re upload the link . it will be usefull to us

    ReplyDelete
  54. heyy can any one can translate this fetch,php in Java/JSP ??

    ReplyDelete
  55. sir please add pagination and search with this code.

    ReplyDelete
  56. You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'AND Event_Level = ''' at line 1

    ReplyDelete