Ajax filter

With reference to this tutorial: Use AJAX to filter MySQL results set (by Pullo)

Dear pullo,

Thanks for posting your code for AJAX filter demo.
I am developing a website for online food order. I have implemented your filter code but I am facing some problems. So I have 3 questions/problems and I have struck up. if you can answer these questions than I shall be really grateful to you.

Your data is populated in the table. What, if I want to populate this data in the Div with designing just in the screenshot attached herewith.

Instead of PDO I use myMySQLi extension for database connectivity so how to change the code ?

I have to use pagination also on the product display page.

Here is the screenshot of my products display page, which is very well designed using DIV’s. I want to apply this AJAX filter on my this page and want the filtered results to be displayed as it is in the current format.

Your help will be highly appreciated.

Thanks & regards,

Sanjay

Hi Sanjay,

One thing at a time:

What does the JSON being returned to the page currently look like?

Please post a sample of a couple of records.

Hi Pullo,
First of all sorry for getting late in reply as it was weekend and I didn’t go to office.

My database structure is as follows -

I have 2 tables with the following structure :-

  1. CREATE TABLE IF NOT EXISTS `sub_categories` (
    

sub_cat_id int(11) NOT NULL AUTO_INCREMENT,
cat_id int(11) DEFAULT NULL,
sub_cat_name varchar(255) DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO sub_categories (sub_cat_id, cat_id, sub_cat_name) VALUES
(1, 1, ‘Dosa’),
(2, 1, ‘Idli’),
(3, 1, ‘Vada’),
(4, 1, ‘Uthappam’),
(5, 1, ‘Rice’);

  1. CREATE TABLE IF NOT EXISTS products (
    prod_id int(11) NOT NULL AUTO_INCREMENT,
    cat_id int(11) DEFAULT NULL,
    sub_cat_id int(11) DEFAULT NULL,
    product_name varchar(255) DEFAULT NULL,
    price int(11) DEFAULT NULL,
    image varchar(255) DEFAULT NULL,
    PRIMARY KEY (prod_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO products (prod_id, cat_id, sub_cat_id, product_name, price, image) VALUES
(1, 1, 1, ‘Plain Dosa’, 100, ‘Plain-Dosa-1.jpg’),
(2, 1, 1, ‘Paper Masala Dosa’, 120, ‘Paper-Masala.jpg’),
(3, 1, 2, ‘Idli Sambar’, 60, ‘idli-sambar.jpg’),
(4, 1, 2, ‘Fried Idli’, 80, ‘fried-idli.jpg’),
(5, 1, 3, ‘Vada Sambar’, 70, ‘vada-sambar.jpg’),
(6, 1, 3, ‘Masala Vada’, 100, ‘masala-vada.jpg’),
(7, 1, 4, ‘Onion Uthappam’, 120, ‘onion-uttapam.jpg’),
(8, 1, 4, ‘Tomato Uthappam’, 150, ‘tomato-uttapam.jpg’),
(9, 1, 5, ‘Lemon Rice’, 90, ‘lemon-rice.jpg’),
(10, 1, 5, ‘Steamed Rice’, 130, ‘steamed-rice.jpg’);

Here is my original file which displays all the products named “product_view.php” and the code is written below. I want to apply AJAX filter on this page based on sub_cat_id (i.e. sub categories). This page also has pagination in it and the pagination file is “functions.php” (which is included in it). The file “includes/functions.php” is a functions file in php for add to cart.

product_view.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>sanjay</title>
<link rel="stylesheet" type="text/css" href="css/style s.css" />
<link rel="stylesheet" type="text/css" href="jcarousel/style.css">
<link href="css/pagination.css" rel="stylesheet" type="text/css" />
<link href="css/B_blue.css" rel="stylesheet" type="text/css" />
<script language="javascript">
	function addtocart(pid){
		document.form1.productid.value=pid;
		document.form1.command.value='add';
		document.form1.submit();
		}
</script>
<?php
require_once 'db_connect.php';
include("includes/functions.php");
include_once ('functions.php');

	if(isset($_REQUEST['command'])){
	if($_REQUEST['command']=='add' && $_REQUEST['productid']>0){
		$pid=$_REQUEST['productid'];
		addtocart($pid,1);
		}
	}
	
	
$page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
    	$limit = 12;
    	$startpoint = ($page * $limit) - $limit;
        
        //to make pagination
        $statement = "`products`";
?>
</head>
<body>
<div class="wapper">
<div class="header">
<?php include('header_new.php'); ?>
</div>
<div class="content">
<div class="row-3">
<div class="colam-p">
<div class="item-row-top-menu">
<a href="index.php">Home</a> > <b>All products</b>
</div>
<div class="item-row">
<div class="wrap1">
<form name="form1">
	<input type="hidden" name="productid" />
    <input type="hidden" name="command" />
</form>
        <?php
            //show records
            $query = mysql_query("SELECT * FROM {$statement} ORDER BY Product_Name LIMIT {$startpoint} , {$limit}");
            
        	while ($row = mysql_fetch_assoc($query)) {
        ?>
        	<div class="productbox">
<div class="innerimagediv"><img src="images1/<?php echo $row['Image'] ?>"width="175" height="103">
</div>
<div class="pu-border-top">
<div class="productcontent"><strong><?php echo $row['Product_Name'] ?></strong>
</div>
</div>
<div class="pu-border-top">
 <label id="txtHint662"><br><lable class="bluerupee">Rs.</lable><strong><?php echo $row['Price'] ?></strong></label>
 </div>

<a href="product_display.php?prod_id=<?php  echo $row['Prod_ID'] ?>" title="Click For View Detail"><img src="images1/learn_more.png" height="30" width="160"></a><br /><p></p>
<a href="#" onclick="addtocart(<?php echo $row['Prod_ID'] ?>)"><img class="buy" src="images1/buy-now.png" alt="" border="0"></a>
</div>
            
        <?php    
            }
        ?>
</div>
<div class="wrap2">
<div align="center">
<?php
	echo pagination($statement,$limit,$page);
?>
</div>
</div>
</div></div>

<div class="right-colum-p">
<div class="ful-border5">
<h2 class="food-cold-btn">Filter Products</h2>
<div class="image-box5">
<ul>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;All Menu</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Dosa</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Idli</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Vada</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Uthappam</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Rice</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Starter</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Bread</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Main Course</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Biryani & Rice</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Dessert</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Salad/Raita</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;North Indian Combo</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;South Indian Combo</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Sandwich</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Burger</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Pasta</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Chinese</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Beverages</li>
<li><input type="checkbox" name="foodmenu" />&nbsp;&nbsp;Pizza</li>
</ul>
</div></div></div>

</div>
</div>
<?php include('footer.php'); ?>
</div>wapper
</body>
</html>

functions.php

<?php

/**
 * @link: http://www.Awcore.com/dev
 */
 
   function pagination($query, $per_page = 10,$page = 1, $url = '?'){        
    	$query = "SELECT COUNT(*) as `num` FROM {$query}";
    	$row = mysql_fetch_array(mysql_query($query));
    	$total = $row['num'];
        $adjacents = "2"; 

    	$page = ($page == 0 ? 1 : $page);  
    	$start = ($page - 1) * $per_page;								
		
    	$prev = $page - 1;							
    	$next = $page + 1;
        $lastpage = ceil($total/$per_page);
    	$lpm1 = $lastpage - 1;
    	
    	$pagination = "";
    	if($lastpage > 1)
    	{	
    		$pagination .= "<ul class='pagination'>";
                    $pagination .= "<li class='details'>Page $page of $lastpage</li>";
    		if ($lastpage < 7 + ($adjacents * 2))
    		{	
    			for ($counter = 1; $counter <= $lastpage; $counter++)
    			{
    				if ($counter == $page)
    					$pagination.= "<li><a class='current'>$counter</a></li>";
    				else
    					$pagination.= "<li><a href='{$url}page=$counter'>$counter</a></li>";					
    			}
    		}
    		elseif($lastpage > 5 + ($adjacents * 2))
    		{
    			if($page < 1 + ($adjacents * 2))		
    			{
    				for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
    				{
    					if ($counter == $page)
    						$pagination.= "<li><a class='current'>$counter</a></li>";
    					else
    						$pagination.= "<li><a href='{$url}page=$counter'>$counter</a></li>";					
    				}
    				$pagination.= "<li class='dot'>...</li>";
    				$pagination.= "<li><a href='{$url}page=$lpm1'>$lpm1</a></li>";
    				$pagination.= "<li><a href='{$url}page=$lastpage'>$lastpage</a></li>";		
    			}
    			elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
    			{
    				$pagination.= "<li><a href='{$url}page=1'>1</a></li>";
    				$pagination.= "<li><a href='{$url}page=2'>2</a></li>";
    				$pagination.= "<li class='dot'>...</li>";
    				for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
    				{
    					if ($counter == $page)
    						$pagination.= "<li><a class='current'>$counter</a></li>";
    					else
    						$pagination.= "<li><a href='{$url}page=$counter'>$counter</a></li>";					
    				}
    				$pagination.= "<li class='dot'>..</li>";
    				$pagination.= "<li><a href='{$url}page=$lpm1'>$lpm1</a></li>";
    				$pagination.= "<li><a href='{$url}page=$lastpage'>$lastpage</a></li>";		
    			}
    			else
    			{
    				$pagination.= "<li><a href='{$url}page=1'>1</a></li>";
    				$pagination.= "<li><a href='{$url}page=2'>2</a></li>";
    				$pagination.= "<li class='dot'>..</li>";
    				for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
    				{
    					if ($counter == $page)
    						$pagination.= "<li><a class='current'>$counter</a></li>";
    					else
    						$pagination.= "<li><a href='{$url}page=$counter'>$counter</a></li>";					
    				}
    			}
    		}
    		
    		if ($page < $counter - 1){ 
    			$pagination.= "<li><a href='{$url}page=$next'>Next</a></li>";
                $pagination.= "<li><a href='{$url}page=$lastpage'>Last</a></li>";
    		}else{
    			$pagination.= "<li><a class='current'>Next</a></li>";
                $pagination.= "<li><a class='current'>Last</a></li>";
            }
    		$pagination.= "</ul>\n";		
    	}
    
    
        return $pagination;
    } 
?>

db_connect.php

<?php

$hostname = 'localhost';
$username = 'root';
$password = '';
$dbname   = 'shopping';

$con = mysql_connect($hostname, $username, $password);
 
if(!$con){
	echo 'My SQL not connected';
}

$sel = mysql_select_db($dbname);

if(!$sel){
	echo "Database not connected";
}
session_start();
?>

includes/functions.php

<?php
	function get_product_name($pid){
		$result=mysql_query("select Product_Name from products where Prod_ID=$pid") or die("select Product_Name from products where Prod_ID=$pid"."<br/><br/>".mysql_error());
		$row=mysql_fetch_array($result);
		return $row['Product_Name'];
	}
	function get_product_image($pid){
		$result=mysql_query("select Image from products where Prod_ID=$pid") or die("select Product_Name from products where Prod_ID=$pid"."<br/><br/>".mysql_error());
		$row=mysql_fetch_array($result);
		return $row['Image'];
	}
	function get_price($pid){
		$result=mysql_query("select Price from products where Prod_ID=$pid") or die("select Product_Name from products where Prod_ID=$pid"."<br/><br/>".mysql_error());
		$row=mysql_fetch_array($result);
		return $row['Price'];
	}
	function remove_product($pid){
		$pid=intval($pid);
		$max=count($_SESSION['cart']);
		for($i=0;$i<$max;$i++){
			if($pid==$_SESSION['cart'][$i]['productid']){
				unset($_SESSION['cart'][$i]);
				break;
			}
		}
		$_SESSION['cart']=array_values($_SESSION['cart']);
	}
	function get_order_total(){
		$max=count($_SESSION['cart']);
		$sum=0;
		for($i=0;$i<$max;$i++){
			$pid=$_SESSION['cart'][$i]['productid'];
			$q=$_SESSION['cart'][$i]['qty'];
			$price=get_price($pid);
			$sum+=$price*$q;
		}
		$_SESSION['subtotal']=$sum;
		return $_SESSION['subtotal'];
	}
	function addtocart($pid,$q){
		
		if($pid<1 or $q<1) return;
		
		if(isset($_SESSION['cart'])){
		if(is_array($_SESSION['cart'])){
			if(product_exists($pid)){ echo "<script>alert('Product already exist in your cart');</script>"; return $pid;}
			$max=count($_SESSION['cart']);
			$_SESSION['cart'][$max]['productid']=$pid;
			$_SESSION['cart'][$max]['qty']=$q;
		}}
		else{
			$_SESSION['cart']=array();
			$_SESSION['cart'][0]['productid']=$pid;
			$_SESSION['cart'][0]['qty']=$q;
		}
		echo "<script>alert('Product has been added to your cart');</script>";
		return $pid;
	}
	function product_exists($pid){
		$pid=intval($pid);
		$max=count($_SESSION['cart']);
		$flag=0;
		for($i=0;$i<$max;$i++){
			if($pid==$_SESSION['cart'][$i]['productid']){
				$flag=1;
				break;
			}
		}
		return $flag;
	}
	
	

?>

For live demo pls visit the link www.ramainfotech.co.in/hungercart/product_view.php

Please help me in getting the Ajax filter on this file alongwith pagination.

Thanks & regards
Sanjay

Lol. You didn’t answer my question.

I edited your reply, as you posted a couple of hundred lines of code I didn’t ask for and you didn’t use code tags. Please do so in future. (to do so, highlight the code and hit the </> button in the editor).

sorry…I couldn’t understand what you are asking… I have posted the complete code here and highlighted it with </>. How can I implement the Ajax filter on it ?

Thanks & regards

Sanjay,

I asked you what the JSON being returned to the page looks like.
I didn’t ask you to dump all of the code you currently have into the thread (although thanks for using proper formatting).

As an aside, just dumping a lot of code on people and saying “Make it work” is one of the better way to ensure that you don’t get a helpful answer.

I have not yet implemented that code in my page as I dont’t know how to and where to put this code in my page as first of all I am not using table, I am using Div and second I am nbot using PDO for DB connection. That’s why I posted the entire code for your kind reference so that you can guide me in a proper manner, as I am not much aware about Ajax.

Please bear with my negligence in Ajax.
Thanks

This is what I have tried to do as per my little knowledge in Ajax.

submit.php

<?php
  $pdo = new PDO('mysql:host=localhost;dbname=shopping', 'root', '');
  $opts = $_POST['filterOpts'];
  $qMarks = str_repeat('?,', count($opts) - 1) . '?';
 
  $statement = $pdo->prepare("SELECT Image, Product_Name, Price, Prod_ID FROM products WHERE Sub_Cat_ID IN ($qMarks)");
  $statement -> execute($opts);
  $results = $statement -> fetchAll(PDO::FETCH_ASSOC);
  $json = json_encode($results);
  echo($json);
?>

product_view.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>sanjay</title>
<link rel="stylesheet" type="text/css" href="css/style s.css" />
<link rel="stylesheet" type="text/css" href="jcarousel/style.css">
<link href="css/pagination.css" rel="stylesheet" type="text/css" />
<link href="css/B_blue.css" rel="stylesheet" type="text/css" />
<script language="javascript">
	function addtocart(pid){
		document.form1.productid.value=pid;
		document.form1.command.value='add';
		document.form1.submit();
		}
</script>
<?php
require_once 'db_connect.php';
include("includes/functions.php");
include_once ('functions.php');

	if(isset($_REQUEST['command'])){
	if($_REQUEST['command']=='add' && $_REQUEST['productid']>0){
		$pid=$_REQUEST['productid'];
		addtocart($pid,1);
		}
	}
 		
$page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
    	$limit = 12;
    	$startpoint = ($page * $limit) - $limit;
        
        //to make pagination
        $statement = "`products`";
?>
</head>
<body>
<div class="wapper">
<div class="header">
<?php include('header_new.php'); ?>
</div>
<div class="content">
<div class="row-3">
<div class="colam-p">
<div class="item-row-top-menu">
<a href="index.php">Home</a> > <b>All products</b>
</div>
<div class="item-row">
<div class="wrap1">
<form name="form1">
	<input type="hidden" name="productid" />
    <input type="hidden" name="command" />
</form>
<table id="phones">
      <tbody>
      </tbody>
    </table>
</div>
<div class="wrap2">
<div align="center">
<?php
	echo pagination($statement,$limit,$page);
?>
</div>
</div>
</div></div>

<div class="right-colum-p">
<div class="ful-border5">
<h2 class="food-cold-btn">Filter Products</h2>
<div class="image-box5">
<ul>
<li><input type="checkbox" id="1">&nbsp;&nbsp;Dosa</li>
<li><input type="checkbox" id="2">&nbsp;&nbsp;Idli</li>
<li><input type="checkbox" id="3">&nbsp;&nbsp;Vada</li>
<li><input type="checkbox" id="4">&nbsp;&nbsp;Uthappam</li>
<li><input type="checkbox" id="5">&nbsp;&nbsp;Rice</li>
<li><input type="checkbox" id="6">&nbsp;&nbsp;Starters</li>
<li><input type="checkbox" id="7">&nbsp;&nbsp;Bread</li>
<li><input type="checkbox" id="8">&nbsp;&nbsp;Main Course</li>
<li><input type="checkbox" id="9">&nbsp;&nbsp;Biryani & Rice</li>
<li><input type="checkbox" id="10">&nbsp;&nbsp;Dessert</li>
<li><input type="checkbox" id="11">&nbsp;&nbsp;Salad/Raita</li>
<li><input type="checkbox" id="12">&nbsp;&nbsp;North Indian Combo</li>
<li><input type="checkbox" id="13">&nbsp;&nbsp;South Indian Combo</li>
<li><input type="checkbox" id="14">&nbsp;&nbsp;Sandwiches</li>
<li><input type="checkbox" id="23">&nbsp;&nbsp;Burger</li>
<li><input type="checkbox" id="31">&nbsp;&nbsp;Pasta</li>
<li><input type="checkbox" id="0">&nbsp;&nbsp;Chinese</li>
<li><input type="checkbox" id="0">&nbsp;&nbsp;Beverage</li>
<li><input type="checkbox" id="0">&nbsp;&nbsp;Pizza</li>
</ul>
</div></div></div>

</div>
</div>
<?php include('footer.php'); ?>
</div><!--wapper-->
<script src="http://code.jquery.com/jquery-latest.js"></script> 
    <script>
      function makeTable(data){
        var tbl_body = "";
        $.each(data, function() {
          var tbl_row = "",
              currRecord = this;

          $.each(this, function(k , v) {
            if(k==='Image'){
              v = "<div class='innerimagediv'>"+"<img height="+103+" width="+175+" src='images1/"+v+"'>" + "</div>";
            } else if (k==='Price'){
              v = "<div class='pu-border-top'>"+"<div class='productcontent'>"+"<font size=3 color=#66C>"+"<B>"+"Rs. "+"</B>"+"</font>"+"<B>"+v+"</B>"+"</div>"+"</div>";
            }
			else if (k==='Product_Name'){
              v = "<div class='pu-border-top'>"+"<div class='productcontent'>"+"<B>"+v+"</B>"+"</div>"+"</div>";
            }
			else if (k==='Prod_ID'){
              v = "";
            }
            tbl_row += "<li>"+v+"</li>";
          })
          tbl_body += "<div class='productbox'>"+"<ul>"+tbl_row+"</ul>"+"<a href='product_display.php?prod_id=" + currRecord['Prod_ID'] +"'" + "title='"+"Click For View Detail"+"'>"+"<img src='images1/"+"learn_more1.png"+"'>"+"</a>"+"<br>"+"<a href='#'"+ "onclick='addtocart(" + currRecord['Prod_ID'] +")'"+">"+"<img class='buy' src='images1/buy-now.png'>"+"</a>"+"</div>";
        })

        return tbl_body;
      }
 
      function getPhoneFilterOptions(){
        var opts = [];
        $checkboxes.each(function(){
          if(this.checked){
            opts.push(this.id);
          }
        });
 
        return opts;
      }
 
      function updatePhones(opts){
        if(!opts || !opts.length){
          opts = allBrands;
        }

        $.ajax({
          type: "POST",
          url: "submit.php",
          dataType : 'json',
          cache: false,
          data: {filterOpts: opts},
          success: function(records){
            $('#phones tbody').html(makeTable(records));
            updatePrices();
          }
        });
      }
      
       function updatePrices(){
        var subsidyTotal = Number($("#total").text());

        $(".price").each(function(){
          var origVal = Number($(this).text())
          $(this).text(origVal - subsidyTotal)
        })
      }

      var $checkboxes = $("input:checkbox");
      $checkboxes.on("change", function(){
        var opts = getPhoneFilterOptions();
        updatePhones(opts);
      });
      
      $("#apply").on("click", function(){
        if(subsidyIsValid()){
          $(this).prop("disabled", true);
          $(this).next().prop("disabled", false);
          updatePrices();
        } else {
          alert("Subsidy invalid!")
        }
      });

      $("#remove").on("click", function(){
        $("#amount1").val("");
        $("#amount2").val("");
        $("#total").text("0");
        $(this).prop("disabled", true);
        $(this).prev().prop("disabled", false);

        $checkboxes.trigger("change");
      });

      var allBrands = [];
      $("input[type=checkbox]").each(function(){
        allBrands.push($(this)[0].id)
      })

      updatePhones();
      updatePrices();
    </script>
</body>
</html>

I don’t know if it is right way or not but I have tried to format the rquired designing in the function “function makeTable(data)”. Pls see. This is giving the same format as on my original page and filter is also working. Just the pagination is not working.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.