Pagination not working in AJAX filter using checkboxes

Continuing the discussion from Use AJAX to filter MySQL results with multiple checkbox option:

I have implemented the code posted by you and is working fine with all the filter options. But facing one problem that I have pagination on this page which is not working. How to make pagination work on this page ?

Below is my code which I have used :

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>

Hi sanjay_tank1975,

You are very complete thatā€™s for sure! Unfortunately Iā€™m tired and that is way too much code for me to sift through I donā€™t even look at my own code that I understand somewhat in such a large bite.

Your question is about AJAX but I see a lot of PHP and Database code. We may very well need that, but for starters please post only the portion you are having a problem with and whatever error messages you are getting.

Thax for your reply. Actually I am developing a website for online food order in PHP & MySQL and have implemented the Ajax filter on my page. And now I am facing problem in applying pagination on it. thatā€™s why I posted my problem here. If someone can help me out in coming out of this problem.,
Thanks

Please post ONLY your AJAX code and any error messages you are getting.

Dear I am not much aware about AJAX as I majorly work on PHP & MySQL. So absolutely having no idea that how to implement Ajax in PHP. My only concern is to make pagination work (which is written in PHP) alongwith AJAX filter on the page. Donā€™t know from where to start ? Am a starter in AJAx.
Thanks

It might be a good time to go learn?
I can recommend this: http://learn.jquery.com/ajax/

1 Like

Dear sir, Thanks for the suggestion. I shall learn it very soon. But at the moment I need to sort out my current problem otherwise I shall loose my job. So please help me in coming out of my problem. Shall be grateful to everyoneā€¦

With all due respect @sanjay_tank1975, there is no way that anyone can help you if you donā€™t understand the basics.
We canā€™t do the job for you. Not only because we donā€™t get paid for that, we volunteer hereā€¦ but we volunteer to help, and to teach. The reason is that guiding and teaching already takes a lot of timeā€¦ thereā€™s no time in the world to do someone elseā€™s job.

I donā€™t know how you got into a situation where you job is in danger. If youā€™re boss is requiring this from you when youā€™re only a backend programmer, then his expectations are unrealistic.

If it was you who promised the Moon when you didnā€™t have a clue how to get it then, obviously thought that you were a better programmer than you really are.

AJAX is, basically, a Javascrript object that request information. You do have the answer in the previous topic but you donā€™t understand itā€¦ You do need to learn the stuff to know whatā€™s going onā€¦ and even if youā€™re a PHP programmer, it still should be ā€œeasyā€ to read for you. Javascript is just another programming language. You do need to get familiar with it. We canā€™t do that for you

4 Likes

Than you should know to start with a limit clause on the query. Just slopping down a bunch of code without any attempt to get things working yourself isnā€™t going to encourage people to help you.

This is my code for pagination in submit.php file but it is not showing any pagination. Couldnā€™t get where is the problem in the code.

submit.php

<?php
require_once('db_connect.php');
$opts = $_POST['filterOpts'];
$tmp = array();
foreach ($opts as $opt) {
$tmp[] = '"'.$opt.'"';
}

$query_ajx1 = "SELECT count(*) FROM products WHERE Sub_Cat_ID IN (".implode(",", $tmp).")";
$result_ajx1 = mysql_query($query_ajx1);
$tot = mysql_fetch_row($result_ajx1);

if(isset($_REQUEST['actionfunction']) && $_REQUEST['actionfunction']!=''){
$limit = 12;
$adjacent = 3;
$actionfunction = $_REQUEST['actionfunction'];
  
   call_user_func($actionfunction,$_REQUEST,$con,$limit,$adjacent);
}
function showData($data,$con,$limit,$adjacent){
	
  $page = $data['page'];
   if($page==1){
   $start = 0;  
  }
  else{
  $start = ($page-1)*$limit;
  }
  $rows = $tot;
  
  
pagination($limit,$adjacent,$rows,$page);  
}
function pagination($limit,$adjacents,$rows,$page){	
	$pagination='';
	if ($page == 0) $page = 1;					//if no page var is given, default to 1.
	$prev = $page - 1;							//previous page is page - 1
	$next = $page + 1;							//next page is page + 1
	$prev_='';
	$first='';
	$lastpage = ceil($rows/$limit);	
	$next_='';
	$last='';
	if($lastpage > 1)
	{	
		
		//previous button
		if ($page > 1) 
			$prev_.= "<a class='page-numbers' href=\"?page=$prev\">previous</a>";
		else{
			//$pagination.= "<span class=\"disabled\">previous</span>";	
			}
		
		//pages	
		if ($lastpage < 5 + ($adjacents * 2))	//not enough pages to bother breaking it up
		{	
		$first='';
			for ($counter = 1; $counter <= $lastpage; $counter++)
			{
				if ($counter == $page)
					$pagination.= "<span class=\"current\">$counter</span>";
				else
					$pagination.= "<a class='page-numbers' href=\"?page=$counter\">$counter</a>";					
			}
			$last='';
		}
		elseif($lastpage > 3 + ($adjacents * 2))	//enough pages to hide some
		{
			//close to beginning; only hide later pages
			$first='';
			if($page < 1 + ($adjacents * 2))		
			{
				for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
				{
					if ($counter == $page)
						$pagination.= "<span class=\"current\">$counter</span>";
					else
						$pagination.= "<a class='page-numbers' href=\"?page=$counter\">$counter</a>";					
				}
			$last.= "<a class='page-numbers' href=\"?page=$lastpage\">Last</a>";			
			}
			
			//in middle; hide some front and some back
			elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
			{
		       $first.= "<a class='page-numbers' href=\"?page=1\">First</a>";	
			for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
				{
					if ($counter == $page)
						$pagination.= "<span class=\"current\">$counter</span>";
					else
						$pagination.= "<a class='page-numbers' href=\"?page=$counter\">$counter</a>";					
				}
				$last.= "<a class='page-numbers' href=\"?page=$lastpage\">Last</a>";			
			}
			//close to end; only hide early pages
			else
			{
			    $first.= "<a class='page-numbers' href=\"?page=1\">First</a>";	
				for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
				{
					if ($counter == $page)
						$pagination.= "<span class=\"current\">$counter</span>";
					else
						$pagination.= "<a class='page-numbers' href=\"?page=$counter\">$counter</a>";					
				}
				$last='';
			}
            
			}
		if ($page < $counter - 1) 
			$next_.= "<a class='page-numbers' href=\"?page=$next\">next</a>";
		else{
			//$pagination.= "<span class=\"disabled\">next</span>";
			}
		$pagination = "<div class=\"pagination\">".$first.$prev_.$pagination.$next_.$last;
		//next button
		
		$pagination.= "</div>\n";		
	}

	echo $pagination;  
}


?>

and this is the AJAX script in

product_view.php

$(function(){
 		$.ajax({
	    url:"submit.php",
        type:"POST",
        data:"actionfunction=showData&page=1",
        cache: false,
        success: function(records){
		   
		  $('#pagination').html(records);
		 
		}
		
	   });
    $('#pagination').on('click','.page-numbers',function(){
       $page = $(this).attr('href');
	   $pageind = $page.indexOf('page=');
	   $page = $page.substring(($pageind+5));
       
	   $.ajax({
	     url:"submit.php",
         type:"POST",
         data:"actionfunction=showData&page="+$page,
        cache: false,
        success: function(records){
		   
		  $('#pagination').html(records);
		 
		}
		
	   });
	return false;
	});
	
});

Not a single intelligent guy here, who can sort out this problem ?
Strange ??

I think that weā€™re more interested here in helping to give you the tools to understand things yourself.
Itā€™s the old give a man a fish parable.

That is what I am also asking sirā€¦Please give me some tool so that I can understand myself and sort out my problem.
Thanks

I have applied your supplied code on my own test server, and have found that some of it refers to test_database and other parts refer to a shopping database, and that the table name is no longer mobile_phones but is instead shopping, and that the table fields are all different names from what you initially supplied.

Can you please resolve this issue first before we carry on with things?

Dear Paul,

First of all I am very sorry for getting late in reply as it was weekend and I couldnā€™t go to office.

Now letā€™s come on the point.

My database structure is as follows -

I have 2 tables with the following structure :-

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ā€™);

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ā€™);

I am filtering the results by sub categories and Below is the file submit.php

<?php
require_once('db_connect.php');
$opts = $_POST['filterOpts'];
$tmp = array();
foreach ($opts as $opt) {
$tmp[] = '"'.$opt.'"';
}
$query_ajx = 'SELECT Image, Product_Name, Price, Prod_ID FROM products WHERE Sub_Cat_ID IN ('.implode(",", $tmp).') ORDER BY Product_Name';
$result_ajx = mysql_query($query_ajx);
$data_ajx = array();
while ($row_ajx = mysql_fetch_assoc($result_ajx)) {
$data_ajx[] = $row_ajx;
}
echo json_encode($data_ajx);
?>

This is working absolutely fine and filtering the results based on sub categories.

I have only 2 issues which I want you to please help me in resolving -

  1. How can I implement pagination on these filtered results.
  2. Just below the sub category filter checkboxes, I want to add 4 checkbox filters for price fo e.g Price < 100 ; Price between 100 & 250 ; Price between 251 & 500 ; Price > 500

Your help will be highly appreciated. Since I didnā€™t change the name of the functions and table, thatā€™s why it is showing mobile_phones/phones.

With regards

Give the checkboxes appropriate values such as filthyrich:

<input type="checkbox" name="begger">
<input type="checkbox" name="lowerclass">
<input type="checkbox" name="bourgeois">
<input type="checkbox" name="filthyrich">

and you can then add them on to the query with something like the following:

$filter = array();
if (isset($_POST['filthyrich'])) {
    array_push($filter, 'Price > 500');
}
...
if (count($filter > 0) {
    $query_ajx += ' WHERE ' + implode(', ', $filter);
}

Iā€™m sure though that the people in the PHP forum may have better ideas on how to implement this.

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