http://larasaget.com/works/sculpture/
You can see it in the bottom of the page Array ( [0] => Resource id #388 [1] => [2] => 5 )
I am not sure how this originated but the pagination is working fine. Only needs to remove the array.
Here is the code from the page template.
ajax-works.php
<?php
$rootD = $_SERVER['DOCUMENT_ROOT'];
include_once($rootD.'/wp-config.php');
if(is_file(dirname(__FILE__) .'/ajaxpaging.php')){
include_once(dirname(__FILE__) .'/ajaxpaging.php');
}elseif(is_file(dirname(__FILE__) .'/../ajaxpaging.php')){
include_once(dirname(__FILE__) .'/../ajaxpaging.php');
}elseif(is_file(dirname(__FILE__) .'/../../ajaxpaging.php')){
include_once(dirname(__FILE__) .'/../../ajaxpaging.php');
}
$ajax_pageing = new get_pageing_ajax();
global $post;
$pageid=$post->ID;;
define(TEMPLATE_URL,get_template_directory_uri()."/");
define(SITE_URL,get_bloginfo('url')."/");
$ajax_page = TEMPLATE_URL."ajax_works.php";
$listdivid = "gallery_div";
$perpage = "6";
if(isset($_REQUEST[gallery_id]) && $_REQUEST[gallery_id]!=""){
$gallery_id=$_REQUEST[gallery_id];
}else{
if($pageid==117)// Performance
$gallery_id=2;
elseif($pageid==374)//Paper
$gallery_id=3;
elseif($pageid==361)//press
$gallery_id=4;
else //Sculpture
$gallery_id=1;
}
$pg_query_string="&gallery_id=".$gallery_id;
$selgallery= "select * from ls_ngg_gallery where gid = ".$gallery_id;
$gres=mysql_query($selgallery);
if(mysql_num_rows($gres)>0)
$galval=mysql_fetch_array($gres);
$sel='SELECT * FROM ls_ngg_pictures WHERE exclude != 1 AND galleryid = '. $gallery_id .' ORDER by pid DESC';
$res = $ajax_pageing->number_pageing($sel,$perpage,0,'N','Y',"",$ajax_page,$pg_query_string,$listdivid);
?>
<div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
<div class="pagetitle"><h1><?php the_title()?></h1></div>
<div class="works">
<?php $total=mysql_num_rows($res[0]);
if($total>0)
{?>
<div class="row">
<?php
while($val=mysql_fetch_array($res[0])){
$secondesc= nggcf_get_field($val[pid], "Second Description");
$thirddesc= nggcf_get_field($val[pid], "Third Description");
?>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-6">
<a rel="lightbox[work_group]" href="<?php echo site_url() . '/' .$galval['path'] . '/' . $val['filename'];?>"
title="<?php echo $val[alttext]?><br /><?php echo $val[description]?><br /><?php echo $secondesc;?><br />
<?php echo $thirddesc?> "><img src="<?php echo site_url() . '/' .$galval['path'] . '/thumbs/thumbs_' . $val['filename']?>"
class="workimage" alt="work_group: image <?php echo $i?> 0f <?php echo $total?> thumb"/></a>
<div class="text-center worktitle">
<?php echo $val[alttext]?>
</div>
</div> <!-- .col-lg-4 .col-md-4 .col-sm-6 .col-xs-6 -->
<?php }?>
</div> <!-- end .row -->
<div class="row">
<div class="col-lg-6"></div>
<div class="col-lg-6 text-right">
</div>
</div>
<?php
}?>
</div>
<div class="clear"></div>
<?php print_r($res); ?>
</div>
ajaxpaging.php
<?php
class get_pageing_ajax{
var $record_per_page=10;
var $pages=5;
var $tbl,$file_names,$order,$query;
///////// GET THE VALUE OF START VARIABLE////////////////
function start()
{
if($_REQUEST["start"])
return $start=$_REQUEST["start"];
else
return $start=0;
}
////////////// END OF START FUNCTION///////////////////
////////////// GET THE CURRENT FILE NAME ///////////////////
function file_names()
{
$pt=explode("/",$_SERVER['SCRIPT_FILENAME']);
$totpt=count($pt);
return $this->file_names=$pt[$totpt-1];
}
////////////// END OF FILE_NAME FUNCTION///////////////////
////////////// DISPLAY THE NUMERIC PAGING WITHOUT RECORD DETAIL///////////////////
function number_pageing_nodetail($query,$record_per_page='',$pages='')
{
return $this->number_pageing($query,$record_per_page,$pages,"N");
}
function number_pageing_bottom_nodetail($query,$record_per_page='',$pages='')
{
return $this->number_pageing($query,$record_per_page,$pages,"N","Y");
}
function number_pageing_bottom($query,$record_per_page='',$pages='')
{
return $this->number_pageing($query,$record_per_page,$pages,"","Y");
}
////////////// END OF NUMERIC PAGING FUNCTION ///////////////////
function runquery($query)
{
return mysql_query($query);
}
function table($result,$titles,$fields,$passfield="",$edit,$delete,$parent="")
{
if($parent=="")
$parent="Y";
if($passfield=="")
$passfield="id";
$cont="<table width='100%' cellspacing='0' cellpadding='3' border='0' class='borders'><tr>";
foreach($titles as $K=>$V)
{
$cont1.="<td";
$cont1.=(is_numeric($V))?" width='$V%' align='center'><strong>$K</strong></td>":" align='center'><strong>$V</strong></td>";
}
$cont.=$cont1."</tr>";
$cont.="<tr><td colspan='".count($titles)."'><script language=javascript>
msg=\"<table border=0 cellpadding=3 cellspacing=1 class='bg1' width='100%'><TR>$cont1</TR></table>\";
</script>
<script src='topmsg.js'></script>
</td></tr>";
$j=0;
while($gets=mysql_fetch_object($result))
{
$j=1;
$cont.="<tr onMouseOver=\"this.className='yellowdark3bdr'\" onmouseout=\"this.className=''\">";
foreach($fields as $K=>$V)
{
$cont.="<td align='center'>";
$tmps=explode(",",$V);
$newval="";
foreach($tmps as $val)
{
$newval.=$gets->$val." ";
}
$cont.=(is_numeric($K))?$newval:"".$newval."";
$cont.=" </td>";
}
$cont.="<td><INPUT name='button' type='button' onClick=\"";
$cont.=($parent=="N")?"window":"parent.body";
$cont.=".location.href='$edit?$passfield=".$gets->$passfield."'\" value='Edit' onMouseOver=\"smsg('Edit This Record -> $newval');return document.prs_return\" onMouseOut=\"nosmsg('Done');return document.prs_return\"> <INPUT onClick=\"deleteconfirm('Are you sure you want to delete this Record?.','$delete?$passfield=".$gets->$passfield."');\" type='button' value='Delete' onMouseOver=\"smsg('Delete This Record -> $newval');return document.prs_return\" onMouseOut=\"nosmsg('Done');return document.prs_return\"> </td>";
$cont.="</tr>";
}
if($j==0)
{
$cont.="<tr><td colspan='".(count($fields)+1)."' align='center'><font color='red'><strong>No Record To Display</strong></font></td></tr>";
}
echo $cont.="</table>";
}
///////////// NUMERIC FUNCTION WITH RECORD DESTAIL//////////////////////////////////////
function number_pageing($query,$record_per_page='',$pages='',$detail='',$bottom='',$simple='',$cur_page="",$query_string="",$divid="")
{
$this->file_names();
$this->query=$query;
if($record_per_page>0)
$this->record_per_page=$record_per_page;
if($pages>0)
$this->pages=$pages;
$this->query=$query;
$result=$this->runquery($this->query);
$totalrows= mysql_affected_rows();
$start=$this->start();
$order=$_GET['order'];
$this->query.=" limit $start,".$this->record_per_page;
$result=$this->runquery($this->query);
$total= mysql_affected_rows();
$total_pages=ceil($totalrows/$this->record_per_page);
$current_page=($start+$this->record_per_page)/$this->record_per_page;
$loop_counter=ceil($current_page/$this->pages);
$start_loop=($loop_counter*$this->pages-$this->pages)+1;
$end_loop=($this->pages*$loop_counter)+1;
if ($current_page > 2)
$start_loop = $current_page-2 ;
if ($total_pages >= $current_page + 3)
{
$end_loop = $current_page + 3;
}
if($end_loop>$total_pages)
$end_loop=$total_pages+1;
$tmpva="";
foreach($_REQUEST as $V=>$K)
{
if($V!="start")
$tmpva.="&".$V."=".$K;
}
//$this->tbl="<table width='100%' border='0' cellpadding='0' cellspacing='0'><tr><td width='15%' align='left'> ";
$this->tbl="<ul class='pagination'>";
if ($cur_page == "")
$cur_page = $this->file_names;
if($start>0)
{
//$this->tbl.="<a class='paging' href='".$cur_page."?start=".($start-$this->record_per_page).$query_string."' class='boldbluelink' onMouseOver=\"smsg('Previous Page');return document.prs_return\" onMouseOut=\"nosmsg('Done');return document.prs_return\"><< Previous</a> ";
$this->tbl.="
<li class='num_off' onclick=call_ajax_view('".$cur_page."','start=".($start-$this->record_per_page).$query_string."','".$divid."')><a>«</a></li>";
}
else
{
$this->tbl.="<li class='num_on'><a>«</a></li>";
}
//$this->tbl.=" </td><td width='70%' align='center' class='bluenormaltahoma'> ";
if($detail!="N" and $simple !="N")
$this->tbl.="Result ".($start+1)." - ".($start+$total)." of ".$totalrows." Records<BR>";
if($simple!='N')
{
for($i=$start_loop;$i<$end_loop;$i++)
{
if($current_page==$i)
{
//$this->tbl.="<span class='currnet_page'>[".$i."]</span> ";
$this->tbl.="<li class='num_on_active'><a>".$i."</a></li>";
}
else
{
//$this->tbl.="<a class='paging' href='".$cur_page."?start=".($i-1)*$this->record_per_page.$query_string."' class='boldbluelink' onMouseOver=\"smsg('View Page Number $i');return document.prs_return\" onMouseOut=\"nosmsg('Done');return document.prs_return\">".$i."</a> ";
$this->tbl.="<li class='num_off' onclick=call_ajax_view('".$cur_page."','start=".($i-1)*$this->record_per_page.$query_string."','".$divid."')><a>".$i."</a></li>";
}
}
}
//$this->tbl.=" </td><td width='15%' align='right'>";
if($start+$this->record_per_page<$totalrows)
{
//$this->tbl.="<a class='paging' href='".$cur_page."?start=".($start+$this->record_per_page).$query_string."' class='boldbluelink' onMouseOver=\"smsg('Next Page');return document.prs_return\" onMouseOut=\"nosmsg('Done');return document.prs_return\">Next >></a>";
$this->tbl.="<li class='num_off' onclick=call_ajax_view('".$cur_page."','start=".($start+$this->record_per_page).$query_string."','".$divid."')><a>»</a></li>";
}
else
{
$this->tbl.="<li class='num_on'><a>»</a></li>";
}
$this->tbl.="</ul>
";
if($bottom=="Y")
{
return $result=array($result,$this->tbl,$total_pages);
}
else
{
echo $this->tbl;
return $result;
}
}
////////////// SIMPLE NEXT-PRI PAGING ///////////////////
function pageing($query,$record_per_page="",$pages="")
{
return $this->number_pageing($query,$record_per_page,$pages,'','','N');
}
////////////// END OF SIMPLE PAGING FUNCTION///////////////////
////////////// WRITE ALL,A TO Z CHARACTER WITH CURRENT PAGE LINK ///////////////////
function order()
{
$this->file_names();
$this->order.="<TR><TD><a class=la href='".$this->file_names."' onMouseOver=\"smsg('View All Records');return document.prs_return\" onMouseOut=\"nosmsg('Done');return document.prs_return\">All</a></TD><TD class=lg>|</TD>";
for($i=65;$i<91;$i++)
{
$this->order.="<TD><a class=la href='$file_names?order=".chr($i)."' onMouseOver=\"smsg('View By ".chr($i)."');return document.prs_return\" onMouseOut=\"nosmsg('Done');return document.prs_return\">".chr($i)."</a></TD><TD class=lg>|</TD>";
}
return $this->order.="</TR>";
}
function MakeCombo($query,$value="",$fill_value,$comboname)
{
if($value=="")
$value=$fill_value;
$run=$this->runquery($query);
$totlist=mysql_affected_rows();
$Combo="<select name='$comboname'>";
$Combo.="<option value=''>----------Select-----------</option>";
for($i=0;$i<$totlist;$i++)
{
$get=mysql_fetch_object($run);
$Combo.="<option value='".$get->$value."'>".$get->$fill_value."</option>";
}
$Combo.="</select>";
echo $Combo;
}
}
?>
Replace
<?php print_r($res); ?>
with
<?php $ajax_pageing->number_pageing($sel,$perpage,0,'N','N',"",$ajax_page,$pg_query_string,$listdivid); ?>
And remove call to number_pageing on top of file.
Calling number_pageing method will echo it. No need to echo or print_r it again.
Related
I have built a search (https://brawlins.com/oer/index.php) and I want to enable user to be able to select filters to limit the search results after their initial search. I have the filters populated in a dropdown menu on my search page (https://brawlins.com/oer/search.php?term=) but I am not sure how to filter down the results once a user clicks on them. I want the users to be able to select multiple options as well. I create a class to store the filters. Below is the code from my filter class:
<?php
class filterContentProvider {
private $conn;
public function __construct($conn) {
$this->conn = $conn;
}
public function getType ($conn) {
$query = $this->conn->prepare("SELECT type, COUNT(*) as total FROM oer_search GROUP BY type");
$query->execute();
$filterHTML .= "<h3 class='filterTitle'>Type</h3>";
$filterHTML .= "<div class'dropdown'>";
$filterHTML .= "<button class='btn btn-filter dropdown-toggle' type='button' id='dropdownMenuButton' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>Select - Type</button>";
$filterHTML .= "<div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton'>";
//$filterHTML .= "<option value=''>- Type -</option>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$type = $row["type"];
$total = number_format($row["total"]);
$filterHTML .= "<a class='dropdown-item' href='search.php?type=$type'>$type ($total)</a>";
}
$filterHTML .= "</div>";
$filterHTML .= "</div>"; //end of dropdown
return $filterHTML;
}
public function getSubject ($conn) {
$query = $this->conn->prepare("SELECT subject, COUNT(*) as total FROM oer_search GROUP BY subject");
$query->execute();
$filterHTML .= "<h3 class='filterTitle'>Subject</h3>";
$filterHTML .= "<div class'dropdown'>";
$filterHTML .= "<button class='btn btn-filter dropdown-toggle' type='button' id='dropdownMenuButton' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>Select - Subject</button>";
$filterHTML .= "<div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton'>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$subject = $row["subject"];
$total = number_format($row["total"]);
if ($subject != "") {
$filterHTML .= "<a class='dropdown-item' href='search.php?subject=$subject'>$subject ($total)</a>";
}
}
$filterHTML .= "</div>";
$filterHTML .= "</div>"; //end of dropdown
return $filterHTML;
}
public function getLicense ($conn) {
$query = $this->conn->prepare("SELECT license, COUNT(*) as total FROM oer_search GROUP BY license");
$query->execute();
$filterHTML .= "<h3 class='filterTitle'>License</h3>";
$filterHTML .= "<div class'dropdown'>";
$filterHTML .= "<button class='btn btn-filter dropdown-toggle' type='button' id='dropdownMenuButton' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>Select - License</button>";
$filterHTML .= "<div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton'>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$license = $row["license"];
$total = number_format($row["total"]);
if ($license != "") {
$filterHTML .= "<a class='dropdown-item' href='index-test.php?license=$license'>$license ($total)</a>";
}
}
$filterHTML .= "</div>";
$filterHTML .= "</div>"; //end of dropdown
return $filterHTML;
}
public function getReviewed ($conn) {
$query = $this->conn->prepare("SELECT review, COUNT(*) as total FROM oer_search GROUP BY review");
$query->execute();
$filterHTML .= "<h3 class='filterTitle'>Reviewed</h3>";
$filterHTML .= "<div class'dropdown'>";
$filterHTML .= "<button class='btn btn-filter dropdown-toggle' type='button' id='dropdownMenuButton' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>Select - Reviewed</button>";
$filterHTML .= "<div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton'>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$review = $row["review"];
$total = number_format($row["total"]);
if ($review != "") {
$filterHTML .= "<a class='dropdown-item' href='index-test.php?review=$review'>$review ($total)</a>";
}
}
$filterHTML .= "</div>";
$filterHTML .= "</div>"; //end of dropdown
return $filterHTML;
}
public function getOrigin ($conn) {
$query = $this->conn->prepare("SELECT source, COUNT(*) as total FROM oer_search GROUP BY source");
$query->execute();
$filterHTML .= "<h3 class='filterTitle'>Source</h3>";
$filterHTML .= "<div class'dropdown'>";
$filterHTML .= "<button class='btn btn-filter dropdown-toggle' type='button' id='dropdownMenuButton' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>Select - Source</button>";
$filterHTML .= "<div class='dropdown-menu scrollable-menu' aria-labelledby='dropdownMenuButton'>";
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$source = $row["source"];
$total = number_format($row["total"]);
if ($source != "") {
$filterHTML .= "<a class='dropdown-item' href='index-test.php?source=$source'>$source ($total)</a>";
}
}
$filterHTML .= "</div>";
$filterHTML .= "</div>"; //end of dropdown
return $filterHTML;
}
}
?>
Here is the code I am using on my search.php page. Any help would be much appreciated.
<?php
include("config.php");
include("classes/siteResultsProvider.php");
include("classes/imageResultsProvider.php");
include("classes/filterContentProvider.php");
include("classes/filterImageProvider.php");
if(isset($_GET["term"])){
$term = $_GET["term"];
}
if(isset($_GET["collection"])){
$collection = $_GET["collection"];
}
else {
$collection = "open_content";
}
$page = isset($_GET["page"]) ? $_GET["page"] : 1;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>SOAR</title>
<?php
include("header.php");
?>
<div class="wrapper">
<div class="header">
<div class="headerContent">
<div class="searchContainer">
<form action="search.php" method="GET">
<div class="searchBarContainer">
<input type="hidden" name="collection" value="<?php echo $collection; ?>">
<input class="searchBox" type="text" name="term" value="<?php echo htmlspecialchars($term, ENT_QUOTES) ?>" aria-label="search box">
<button class="searchButton">
<img src="images/search-icon.png" alt="search icon">
</button>
</div>
</form>
</div>
</div><!--end of headerContent-->
<div class="tabsContainer">
<ul class="tabList">
<li class="<?php echo $collection == 'open_content' ? 'active' : '' ?>">
</i> Open Content
</li>
<li class="<?php echo $collection == 'images' ? 'active' : '' ?>">
</i> Images
</li>
</ul>
</div>
</div><!--end of header-->
<!-------------------------beginning of main section where seach results will display-------------------------->
<?php
if($collection == "open_content") {
$filters = new filterContentProvider($conn);
}
else {
$filters = new filterImageProvider($conn);
}
if($collection == "open_content") {
$filterType = $filters->getType($conn);
$filterSubject = $filters->getSubject($conn);
$filterOrigin = $filters->getOrigin($conn);
$fitlerLicense = $filters->getLicense($conn);
$filterReviewed = $filters->getReviewed($conn);
echo "<div class='filterContainer'>
<div class='filterContent'>
<div class='filter'>
$filterType
</div>
<div class='filter'>
$filterSubject
</div>
<div class='filter'>
$filterOrigin
</div>
<div class='filter'>
$fitlerLicense
</div>
<div class='filter'>
$filterReviewed
</div>
</div>
</div>";
}
else {
$imageFilterOrigin = $filters->getImageOrigin($conn);
$imageFilterLicense = $filters->getImageLicense($conn);
echo "<div class='filterContainer'>
<div class='filterContent'>
<div class='filter'>
$imageFilterOrigin
</div>
<div class='filter'>
$imageFilterLicense
</div>
</div>
</div>";
}
?>
<div class="mainResultsSection">
<?php
if($collection == "open_content") {
$resultsProvider = new siteResultsProvider($conn);
$pageSize = 25;
}
else {
$resultsProvider = new imageResultsProvider($conn);
$pageSize = 50;
}
$numResults = $resultsProvider->getNumResults($term);
echo "<p class='resultsCount'>" . number_format($numResults) . " results found</p>";
echo $resultsProvider->getResultsHTML($page, $pageSize, $term);
?>
</div>
<div class="paginationContainer">
<div class="pageButtons">
<div class="pageNumberContainer">
<img src="images/pageStart.png" alt="Start of page image">
</div>
<?php
$pagesToShow = 10;
$numPages = ceil($numResults / $pageSize);
$pagesLeft = min($pagesToShow, $numPages);
$currentPage = $page - floor($pagesToShow / 2);
if($currentPage < 1) {
$currentPage = 1;
}
if($currentPage + $pagesLeft > $numPages + 1) {
$currentPage = $numPages + 1 - $pagesLeft;
}
while($pagesLeft != 0 && $currentPage <= $numPages) {
if($currentPage == $page) {
echo "<div class='pageNumberContainer'>
<img src='images/pageSelected.png' alt='selected page page image'/>
<span class='pageNumber'>$currentPage</span>
</div>";
}
else {
echo "<div class='pageNumberContainer'>
<a href='search.php?term=$term&collection=$collection&page=$currentPage'>
<img src='images/page.png' alt='pages image'/>
<span class='pageNumber'>$currentPage</span>
</a>
</div>";
}
$currentPage++;
$pagesLeft--;
}
?>
<div class="pageNumberContainer">
<img src="images/pageEnd.png" alt="End of page image">
</div>
</div>
</div><!--end of pagination container-->
</div><!--end of wrapper-->
<script src="https://cdn.jsdelivr.net/gh/fancyapps/fancybox#3.5.7/dist/jquery.fancybox.min.js"></script>
<script src="https://unpkg.com/masonry-layout#4/dist/masonry.pkgd.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</body>
</html>
It seems like you'd want to do a couple of things to get this working.
If you want the results to be asynchronous:
Add an onchange event to you select inputs. (something like onchange="addFilter('type', this.value)") See https://www.w3schools.com/jsref/event_onchange.asp
Have the onchange function (addFilter) send the filters and query string back to your PHP script via an AJAX request. If you're using jQuery, the get method would work for you. https://api.jquery.com/jquery.get/
Pull the new results in PHP using the $_GET parameters you've passed. (Like you are already doing in your script.) You'll want to echo out just the results--not the navigation and other elements of the page.
Update the search results on the page using (something like $('#myContainer').html(results); in jQuery)
Additionally, it would be good to update the URL params in the location bar How do I modify the URL without reloading the page?
Here's a really simple example:
test.php
<?php
// Look up the results here
// You'll probably want to do something more performant that this; it's just a lazy example. :)
// ...
$query = $this->conn->prepare("SELECT type, COUNT(*) as total FROM oer_search WHERE type LIKE :type AND subject LIKE :subject GROUP BY type");
$query->execute([
'type' => isset($_GET['type'] ? $_GET['type'] : '%',
'subject' => isset($_GET['subject'] ? $_GET['subject'] : '%',
]);
// ...
?>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="jquery-3.4.1.min.js"></script>
<script>
function addFilter(name, value) {
var url = '/test.php?';
var urlParams = new URLSearchParams(window.location.search);
var keys = urlParams.keys();
for(key of keys) {
if (key == name) {
continue;
}
url += key + '=' + urlParams.get(key) + '&';
}
url += name + '=' + value;
window.history.pushState({}, "", );
$.get(url, function(data) {
$('#results').html(data);
});
}
</script>
</head>
<body>
<select onchange="addFilter('type', this.value)">
<option></option>
<option>value 1</option>
<option>value 2</option>
</select>
<select onchange="addFilter('subject', this.value)">
<option></option>
<option>value 1</option>
<option>value 2</option>
</select>
<div id="results"></div>
</body>
</html>
If you don't care/want the page to reload:
Just make the onchange event submit the form with the search parameters again. If you use jQuery, the submit method would work. Be sure to select the options appropriately in the select inputs, or they'll clear out each time (making it impossible to set more than one).
I want to display long notes on bootstrap carousel. the notes will be fetched from mySql database. Since the notes are long, i need to split them using number of words then display them in the carousel slides. the problems is that am not able to display the splitted text in different slides. the following is what i have done:
<div class="col-md-6 ">
<div class="panel panel-primary">
<div class="panel-heading">Lecture</div>
<!-- Slider News by Carousel -->
<div id='myCarousel' class='carousel slide' data-ride='carousel'>
<ol class='carousel-indicators'>
<?php
include "config/koneksi.php";
$query = "select notes from notes where Note_ID = 34";
$res = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($res)) {
$w = $row['notes'];
$arr2 = str_split($w, 500);
}
//var_dump($arr2);
$max = sizeof($arr2);
$slides = '';
$Indicators = '';
$counter = 0;
?>
</ol>
<div class='carousel-inner'>
<?php
for ($x = 0; $x <= $max; $x++) {
if ($x == 0) {
echo "<div class='item active'>";
echo $arr2[$x]++;
echo "</div>";
} else {
echo "<div class='item'>";
if (!isset($arr2[$x])) {
$arr2[$x] = 0;
}
echo $arr2[$x]++;
echo "</div>";
}
}
echo "</div>";
echo "<a class='left carousel-control' href='#myCarousel' data-slide='prev'>‹</a>";
echo "<a class='right carousel-control' href='#myCarousel' data-slide='next'>›</a>";
echo "</div>";
echo "<!-- End Slider Caraousel-->";
?>
</div>
</div>
</div>
</div>
the result:
the result
I am trieng to list item form the database, however, the result comes out in two. 2 result is displayed for each record. currently i only have one record in the database but when i display them on the screen it is repaeted. i do not know why this is happening, i have tried to palce a counter and see how many times the loop goes on and the result is always once. however the result is displayed two times.
the code as follows:
<section class="container">
<div class="row">
<?php
if($bidCollection->selectBidsByStatusAndAppId(BidAccount::OPEN_NEW, $id)){
foreach($bidCollection->getBids() as $bid){
$banker->find($bid->getCustomerId());
$counter=0;
?>
<div class='col-xs-12 bg-more-light-gray bidlist'>
<div class="col-xs-12 col-sm-1 col-md-1">
<?php
if(!$uploader->findProfilePicture($banker->data()->_customer_id)){
echo "<img src='image/holder.png ' width='50' height='50' class='img-responsive' />";
}else{
echo "<img src='upload/proPicture/".$uploader->data()->pictureUrl."' width='50' height='50' class='img-responsive'/>";
}
?>
</div>
<div class="col-xs-12 col-sm-8 col-md-8">
<?php
echo '<h2>Agent name :'.$validate->cleanInput($banker->data()->officer_name).'</h2>';
echo '<h3>Institute name : '.$validate->cleanInput($banker->data()->bank_name).' '.++$counter.'</h3>';
if($bid->getApplicationOwnerId() === $customer->data()->_customer_id){
echo "<p>CheckBook: ";
if($bid->getRequestCheckBook()){echo "Yes";}else{echo "No";}
echo "</p>";
echo"<p> Minimum Deposit: AED ".$bid->getMinDeposit()."</p>";
echo"<p> Direct Debit Card: ";
if($bid->getRequestCreditCard()){echo "Yes";}else{echo "No";}
echo "</p>";
echo"<p> Other Fees / Arrangement Fees: AED ".$bid->getFees(). "</p>";
echo"<p> Account Will be ready in: ".$bid->getSetupTime() ."</p>";
}
?>
</div>
<div class="col-xs-12 col-sm-2 col-md-2">
<?php
$datetime = new DateTime($bid->getDatePosted());
$date = $datetime->format('Y-m-d');
$time = $datetime->format('H:i:s');
echo '<h4> Date: '.$date.'<br/>Time: '.$time.'</h4>';
echo"<form method='POST' action='viewBanker.php'>";
echo "<input type='hidden' name='banker' value='".$bid->getCustomerId()."'>";
echo "<input type='submit' class ='btn btn-default' name='submit' value='View Profile'>";
echo "</form>";
echo'<br/>';
if($bid->getApplicationOwnerId() === $customer->data()->_customer_id){
echo"<form method='post' action='acceptAccountBid.php'>";
echo "<input type='hidden' value='".$bid->getCustomerId()."' name ='bankerId'/>";
echo "<input type='hidden' value='".$id."' name ='appid'/>";
echo "<input type='hidden' value='".$bid->getApplicationOwnerId()."' name='ownerId'>";
echo "<input class='btn btn-default' type='submit' value='Accept Offer' name='submit'>";
echo"</form>";
}
?>
</div>
</div>
<?php
}
}
?>
The Methods that returns the the values is as follows:
public function selectBidsByStatusAndAppId($status, $appid)
{
$sql = "SELECT * FROM accountBid WHERE application_id = :appId AND status = :st";
try {
$sth = $this->_db->getConnection()->prepare($sql);
$sth->bindValue(':appId', $appid);
$sth->bindValue(':st', $status);
$sth->execute();
} catch (Exception $e) {
$this->setAlert('danger', 'Information Presentation Error: ' . $e->getMessage());
}
foreach ( $sth->fetchAll(PDO::FETCH_ASSOC) as $data) {
$this->addBid($data);
}
return true;
}
public function addBid($data = null)
{
$bid = new BidAccount($data);
$this->bids[] = $bid;
}
public function getBids()
{
return $this->bids;
}
first of all, I want to thank my mates who tried to help me earlier. the problem was I had another function which I forgot to post it here bidExist()
public function bidExist( $appId , $id){
$sql = "SELECT * FROM accountBid WHERE application_id = :appId AND _customer_id = :id";
try {
$sth = $this->_db->getConnection()->prepare($sql);
$sth->bindValue(':appId', $appId);
$sth->bindValue(':id', $id);
$sth->execute();
} catch (Exception $e) {
$this->setAlert('danger', 'Information Presentation Error: ' . $e->getMessage());
}
foreach ( $sth->fetchAll(PDO::FETCH_ASSOC) as $data) {
$this->addBid($data);
}
return $sth->rowCount();
}
The function above looped through the collection to check and see if the object exists before this and if it is then you can not add anymore bid, however, i forgot to remove the addBid() function on this method and that cause the object to be added twice to the collection. This took me the whole night to figure out. but I thank everyone who tried to support and assist.
I am trying to apply delete function on selected record in my application. the problem is that the record are displayed in pagination ie 3,4 rows, i am able to delete record from the first page but when i move to the second page and select few records, the delete record buton doesn't work. any adivise will really help.
I am looking for replies
here is my code for listings
public function index($offset=0)
{
if ( $this->session->userdata('u_name') == FALSE )
{
$data['page_title']="Admin Login";
redirect('admin/login',"refresh",$data);
}
$this->load->model('candidate_model');
$limit=4;
$results=$this->candidate_model->get_all_Candidate($limit,$offset);
$data['candidates']=$results['rows'];
$offset = $this->uri->segment(3, 0);
$data['num_results']=$results['num_rows'];
$this->load->library('pagination');
$config=array();
$config['first_url'] = 'candidateList/index';
$config['base_url']=site_url('candidateList/index');
$config['total_rows']=$data['num_results'];
$config['per_page']=$limit;
$config['uri_segment']=3;
$config['first_link'] = '>';
$config['first_tag_open'] = '<div>';
$config['first_tag_close'] = '</div>';
$this->pagination->initialize($config);
$data['page_title']="Candidate List";
$this->load->view('manageCandidate',$data);
}
my code for delete function is bellow
if($this->input->post('Delete')=='Delete')
{
for($i=0;$i<count($_POST['checkbox']);$i++)
{
$candidate_id = $_POST['checkbox'][$i];
$this->candidate_model->deleteCandidate($candidate_id);
$this->session->set_flashdata('deleteSelected','Selected Candidate has been deleted.');
}
$data['page_title']="Candidate List";
redirect('candidateList',$data);
}
Delete function is here:
public function candidate()
{
if ( $this->session->userdata('u_name') == FALSE )
{
$data['page_title']="Admin Login";
redirect('admin/login',"refresh",$data);
}
$checkList=$this->input->post('checkbox');
$this->load->model('candidate_model');
if($checkList!=NULL)
{
if($this->input->post('Delete')=='Delete')
{
for($i=0;$i<count($_POST['checkbox']);$i++)
{
$candidate_id = $_POST['checkbox'][$i];
$this->candidate_model->deleteCandidate($candidate_id);
$this->session->set_flashdata('deleteSelected','Selected Candidate has been deleted.');
}
$data['page_title']="Candidate List";
redirect('candidateList',$data);
}
else if($this->input->post('Email')=='Email')
{
for($i=0;$i<count($_POST['checkbox']);$i++)
{
$admin_id = $_POST['checkbox'][$i];
$email_to[$i] = $_POST['checkbox'][$i];
$data['email_to'] = $email_to;
}
$data['page_title']='Send Mail';
$this->load->view('admin/sendmail4',$data);
}
}
else
{
$this->session->set_flashdata('deleteSelect','Please Select at-least one Candidate.');
$data['page_title']="Candidate List";
redirect('candidateList',$data);
}
}
ManageCandidate code:
<?php
$this->load->view('includes/template3');
?>
<?php
$this->load->view('includes/superAdminMenu');
?>
<div class="dashboard">
Add Candidate
<?php if($this->session->flashdata('deleteCandidate')) : ?>
<p class="successMsg"><?php echo $this->session->flashdata('deleteCandidate')?></p>
<?php endif; ?>
<?php if($this->session->flashdata('editCandidate')) : ?>
<p class="successMsg"><?php echo $this->session->flashdata('editCandidate')?></p>
<?php endif; ?>
<?php if($this->session->flashdata('deleteSelected')) : ?>
<p class="successMsg"><?php echo $this->session->flashdata('deleteSelected')?></p>
<?php endif; ?>
<?php if($this->session->flashdata('deleteSelect')) : ?>
<p class="noRows"><?php echo $this->session->flashdata('deleteSelect')?></p>
<?php endif; ?>
<?php if($this->session->flashdata('msgSent')) : ?>
<p class="successMsg"><?php echo $this->session->flashdata('msgSent')?></p>
<?php endif; ?>
<?php
if($num_results==0)
{ ?>
<p class="noRows"><?php echo "You have not added any Candidate.";?></p>
<?php }
else
if($num_results>0)
{ ?>
<form action="candidateList/candidate" method="post" name="sendMail" class="addformClass" id="candidateList1">
<!-- Script by hscripts.com -->
<!-- copyright of HIOX INDIA -->
<!-- Free javascripts # http://www.hscripts.com -->
<script type="text/javascript">
checked=false;
function checkedAll (candidateList1) {
var aa= document.getElementById('candidateList1');
if (checked == false)
{
checked = true
}
else
{
checked = false
}
for (var i =0; i < aa.elements.length; i++)
{
aa.elements[i].checked = checked;
}
}
</script>
<!-- Script by hscripts.com -->
<?php if(isset($candidates)) { ?>
<div class="candidateTable">
<div class="candidateRowHeading">
<div class="candidateHeadingChkBox">
<h4><input type='checkbox' name='checkall' onclick='checkedAll(candidateList1);'>
</h4>
</div><!--END candidateHeadingChkBox-->
<div class="candidateColHeading1">
<h4>Candidate Name</h4>
</div><!--END candidateColHeading1-->
<div class="candidateColHeading3">
<h4>Email</h4>
</div><!--END candidateColHeading3-->
<div class="candidateColHeading4" style="display:none">
<h4>Status</h4>
</div><!--END candidateColHeading4-->
<div class="candidateColHeading6">
<h4>Recruiter Assigned</h4>
</div><!--END candidateColHeading6-->
<div class="candidateColHeading5">
<h4>Action</h4>
</div><!--END candidateColHeading5-->
</div><!--END candidateRowHeading-->
<?php $count=0; ?>
<?php foreach ($candidates as $candidate) { ?>
<div class="candidateRowData">
<div class="candidateColChkBox">
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<?php echo $candidate->candidate_id; ?>">
</div><!--END candidateColChkBox-->
<div class="candidateColData1">
<?php echo anchor('admin/viewCandidate/'.$candidate->candidate_id, $candidate->first_name." ".$candidate->last_name); ?>
</div><!--END candidateColData1-->
<div class="candidateColData3">
<h4><?php echo $candidate->email; ?></h4>
</div><!--END candidateColData3-->
<div class="candidateColData4" style="display:none">
<h4><?php echo $candidate->lead_status; ?></h4>
</div><!--END candidateColData4-->
<div class="candidateColData6">
<h4>
<?php if($candidate->recruiter_id_fk!=0) { ?>
<?php echo get_recruiterFirstName($candidate->recruiter_id_fk); ?>
<?php echo get_recruiterLastName($candidate->recruiter_id_fk); ?>
<?php echo " (<strong>"; ?>
<?php echo get_recruiterLogin($candidate->recruiter_id_fk); ?>
<?php echo "</strong>) "; ?>
<?php }
else if($candidate->recruiter_id_fk==0) { ?>
<?php echo "Not Assigned"; ?>
<?php } ?>
</h4>
</div><!--END candidateColData6-->
<div class="candidateColData5">
<?php echo anchor('admin/editCandidate/'.$candidate->candidate_id,'Edit'); ?>
<?php echo anchor('admin/deleteCandidate/'.$candidate->candidate_id,'Delete'); ?>
</div><!--END candidateColData5-->
</div><!--END candidateRowData-->
<?php $count++; } ?>
</div><!--END candidateTableCom-->
<?php } ?>
<?php } ?>
<?php if(isset($candidates)) { ?>
<div id="pageNum">
<?php echo $this->pagination->create_links(); ?>
</div>
<?php } ?>
<?php
if($num_results>0) {
echo '<input type="submit" name="Delete" class="emailAllBtn" value="Delete" />';
echo '<input type="submit" name="Email" class="emailAllBtn" value="Email" />';
echo "</form>";
} ?>
</div>
<?php
$this->load->view('includes/footer2');
?>
<?php
function get_recruiterFirstName($id)
{
$CI =& get_instance();
$mod = $CI->load->model('recruiter_model');
$count = $CI->recruiter_model->get_recruiterFirstName($id);
return $count;
}
?>
<?php
function get_recruiterLastName($id)
{
$CI =& get_instance();
$mod = $CI->load->model('recruiter_model');
$count = $CI->recruiter_model->get_recruiterLastName($id);
return $count;
}
?>
<?php
function get_recruiterLogin($id)
{
$CI =& get_instance();
$mod = $CI->load->model('recruiter_model');
$count = $CI->recruiter_model->get_recruiterLogin($id);
return $count;
}
?>
Small mistake exist in your pagination code offset value correct it
public function index($offset=0)
{
if ( $this->session->userdata('u_name') == FALSE )
{
$data['page_title']="Admin Login";
redirect('admin/login',"refresh",$data);
}
$this->load->model('candidate_model');
$limit=4;
//whenever you are calling this pagination offset value you need to fetch it from URL
$offset_url = $offset = $this->uri->segment(3, 0);
//if it's not exist take the default value
$offset = is_numeric($offset_url)?$offset_url:$offset;
$results=$this->candidate_model->get_all_Candidate($limit,$offset);
$data['candidates']=$results['rows'];
..............
}
I am working on a search,filter operation using php,mysql.
My classes for pagination are
class Paginator{
var $items_per_page;
var $items_total;
var $current_page;
var $num_pages;
var $mid_range;
var $low;
var $limit;
var $return;
var $default_ipp;
//var $querystring;
var $ipp_array;
function Paginator()
{
$this->current_page = 1;
$this->mid_range = 2;
$this->ipp_array = array(2,4,6,8,10,'All');
$this->items_per_page = (!empty($_GET['ipp'])) ? $_GET['ipp']:$this->default_ipp;
}
function paginate()
{
if(!isset($this->default_ipp)) $this->default_ipp='2';
if($_GET['ipp'] == 'All')
{
$this->num_pages = 1;
//$this->items_per_page = $this->default_ipp;
}
else
{
if(!is_numeric($this->items_per_page) OR $this->items_per_page <= 0) $this->items_per_page = $this->default_ipp;
$this->num_pages = ceil($this->items_total/$this->items_per_page);
}
$this->current_page = (isset($_GET['page'])) ? (int) $_GET['page'] : 1 ; // must be numeric > 0
$prev_page = $this->current_page-1;
$next_page = $this->current_page+1;
if($_GET)
{
$args = explode("&",$_SERVER['QUERY_STRING']);
foreach($args as $arg)
{
$keyval = explode("=",$arg);
if($keyval[0] != "page" And $keyval[0] != "ipp") $this->querystring .= "&" . $arg;
}
}
if($_POST)
{
foreach($_POST as $key=>$val)
{
if($key != "page" And $key != "ipp") $this->querystring .= "&$key=$val";
}
}
if($this->num_pages > 4)
{
$this->return = ($this->current_page > 1 And $this->items_total >= 10) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$prev_page&ipp=$this->items_per_page$this->querystring\">« Previous</a> ":"<span class=\"inactive\" href=\"#\">« Previous</span> ";
$this->start_range = $this->current_page - floor($this->mid_range/2);
$this->end_range = $this->current_page + floor($this->mid_range/2);
if($this->start_range <= 0)
{
$this->end_range += abs($this->start_range)+1;
$this->start_range = 1;
}
if($this->end_range > $this->num_pages)
{
$this->start_range -= $this->end_range-$this->num_pages;
$this->end_range = $this->num_pages;
}
$this->range = range($this->start_range,$this->end_range);
for($i=1;$i<=$this->num_pages;$i++)
{
if($this->range[0] > 2 And $i == $this->range[0]) $this->return .= " ... ";
// loop through all pages. if first, last, or in range, display
if($i==1 Or $i==$this->num_pages Or in_array($i,$this->range))
{
$this->return .= ($i == $this->current_page And $_GET['page'] != 'All') ? "<a title=\"Go to page $i of $this->num_pages\" class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" title=\"Go to page $i of $this->num_pages\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page$this->querystring\">$i</a> ";
}
if($this->range[$this->mid_range-1] < $this->num_pages-1 And $i == $this->range[$this->mid_range-1]) $this->return .= " ... ";
}
$this->return .= (($this->current_page < $this->num_pages And $this->items_total >= 10) And ($_GET['page'] != 'All') And $this->current_page > 0) ? "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$next_page&ipp=$this->items_per_page$this->querystring\">Next »</a>\n":"<span class=\"inactive\" href=\"#\">» Next</span>\n";
$this->return .= ($_GET['page'] == 'All') ? "<a class=\"current\" style=\"margin-left:10px\" href=\"#\">All</a> \n":"<a class=\"paginate\" style=\"margin-left:10px\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All$this->querystring\">All</a> \n";
}
else
{
for($i=1;$i<=$this->num_pages;$i++)
{
$this->return .= ($i == $this->current_page) ? "<a class=\"current\" href=\"#\">$i</a> ":"<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=$i&ipp=$this->items_per_page$this->querystring\">$i</a> ";
}
$this->return .= "<a class=\"paginate\" href=\"$_SERVER[PHP_SELF]?page=1&ipp=All$this->querystring\">All</a> \n";
}
$this->low = ($this->current_page <= 0) ? 0:($this->current_page-1) * $this->items_per_page;
if($this->current_page <= 0) $this->items_per_page = 0;
$this->limit = ($_GET['ipp'] == 'All') ? "":" LIMIT $this->low,$this->items_per_page";
}
function display_items_per_page()
{
$items = '';
if(!isset($_GET[ipp])) $this->items_per_page = $this->default_ipp;
foreach($this->ipp_array as $ipp_opt) $items .= ($ipp_opt == $this->items_per_page) ? "<option selected value=\"$ipp_opt\">$ipp_opt</option>\n":"<option value=\"$ipp_opt\">$ipp_opt</option>\n";
return "<span class=\"paginate\">Items per page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page=1&ipp='+this[this.selectedIndex].value+'$this->querystring';return false\">$items</select>\n";
}
function display_jump_menu()
{
for($i=1;$i<=$this->num_pages;$i++)
{
$option .= ($i==$this->current_page) ? "<option value=\"$i\" selected>$i</option>\n":"<option value=\"$i\">$i</option>\n";
}
return "<span class=\"paginate\">Page:</span><select class=\"paginate\" onchange=\"window.location='$_SERVER[PHP_SELF]?page='+this[this.selectedIndex].value+'&ipp=$this->items_per_page$this->querystring';return false\">$option</select>\n";
}
function display_pages()
{
return $this->return;
}
}
?>
I have performed a filter using check boxes like this:
<input type="checkbox" id="checkbox1" class="checkbox1" value="<?php echo $suburb['suburb_name']?>" name="Suburb_check[]" onClick="changeResults();" onChange="" ><?php echo $suburb['suburb_name']?> <span class="grey">(<?php echo $suburb['total']?>)</span>
Javascript/ajax code for filter
function changeResults(){
var data = { 'venue[]' : []};
$("input:checked").each(function() {
var chck1 = $(this).val();
//alert(chck1);
data['venue[]'].push($(this).val());
});
$.ajax({
type : 'POST',
url : 'process.php',
data : data,
success : function(data){
$('#project_section').html(data); // replace the contents coming from php file
}
});
}
process.php file
include_once("includes/classes/db_connect.php");
include_once("pagination/paginator.class.php");
$pages = new Paginator();
$value= array();
foreach($_POST as $key=>$value)
{
$value[] = $venue[$key][$value];
}
$countArray = count($value);
//echo $countArray;
/*echo "<pre>";
print_r($value);
echo "</pre>";
exit;*/
if($countArray=='2')
{
$where = "cities.city_name like '%".$_SESSION['$cityName']."%' and suburbs.suburb_name ='".$value[0]."' ";
}
else if($countArray=='3')
{
$where = "cities.city_name like '%".$_SESSION['$cityName']."%' and (suburbs.suburb_name ='".$value[0]."' or suburbs.suburb_name ='".$value[1]."')";
}
else if($countArray=='4')
{
$where = "cities.city_name like '%".$_SESSION['$cityName']."%' and (suburbs.suburb_name ='".$value[0]."' or suburbs.suburb_name ='".$value[1]."' or suburbs.suburb_name ='".$value[2]."')";
}
else if($countArray=='5')
{
$where = "cities.city_name like '%".$_SESSION['$cityName']."%' and (suburbs.suburb_name ='".$value[0]."' or suburbs.suburb_name ='".$value[1]."' or suburbs.suburb_name ='".$value[2]."' or suburbs.suburb_name ='".$value[3]."')";
}
else{
$where = "cities.city_name like '%".$_SESSION['$cityName']."%' " ;
}
$countSql="SELECT count(*) as total from properties inner join cities on properties.city_id=cities.city_id inner join suburbs on properties.suburb_id=suburbs.suburb_id where ".$where." ";
//echo $countSql;
$resultCount = mysql_query($countSql);
$data = mysql_fetch_row($resultCount);
$pages->items_total = $data[0];
$pages->mid_range = 2;
$pages->paginate();
echo $pages->display_pages();
echo $pages->display_items_per_page();
$sql="SELECT * from properties inner join cities on properties.city_id=cities.city_id inner join suburbs on properties.suburb_id=suburbs.suburb_id where ".$where." $pages->limit";
//echo $sql;
$result = mysql_query($sql);
//$data = mysql_fetch_assoc($result);
/*echo "<pre>" ;
print_r($data);
echo "</pre>" ; */
while($row=mysql_fetch_assoc($result))
{
?>
<div class="projectlisttiger" id="propertyList">
<div class="spacer5"> </div>
<div class="listnewimg flt">
<a href="p-kolte-patil-cilantro-wagholi-pune.php">
<img src="admin/uploads/<?php echo ($row['property_cover_image']) ?>" width="186" height="125" border="0">
<!--<img src="admin/uploads/Cilantra1/1cilantra-large.jpg" width="186" height="125" border="0">-->
</a>
<!--<div class="newlistlaunch"><img width="65" height="65" border="0" src="images/projects/kolte-patil/cilantra/new_launch_blue.png">
</div>-->
</div>
<div class="listright">
<div style="width:498px; height:42px;" class="flt">
<div class="list-logo flt">
<div class="buildborder"><img width="80" height="36" border="0" align="absmiddle" alt="Kolte Patil" src="admin/uploads/<?php echo $row['builder_logo']?>">
</div>
<div class="tablistname"><?php echo $row['property_name'] ?></div>
</div>
<?php if ($row['property_price_min']!=0) { ?>
<div class="listprice">
<img width="18" height="18" align="absmiddle" src="images/city/rupee_icon.gif"> <?php echo $row['property_price_min'] ?> Lacs - <?php echo $row['property_price_max'] ?> Lacs
</div>
<?php } else { ?>
<div class="listprice">
<img width="18" height="18" align="absmiddle" src="images/city/rupee_icon.gif">Price on Request
</div>
<?php } ?>
</div>
<div class="spacer3"> </div>
<div class="listbox">
<a href="p-kolte-patil-cilantro-wagholi-pune.php"><strong>Address</strong>:<?php echo $row['locality_name'] ?>, <?php echo $row['city_name'] ?><br> <strong>Types</strong>: 2BHK & 3BHK
<br><strong>Sizes:</strong> <?php echo $row['property_size_min'] ?> sqft - <?php echo $row['property_size_max'] ?> sqft </a>
</div>
<div style="margin-left:-3px;" class="flt">
<div style="width:110px;" class="flt"><a style="text-decoration:none;" href="p-kolte-patil-cilantro-wagholi-pune.php"><input type="button" value="View Details" class="detail_project"></a>
</div>
<div style="width:110px;" class="flt"><input type="button" onClick="showEnqForm('2659','Cilantro'); return false;" value="Enquire Now" class="enquire_project"></div>
</div>
<div class="spacer"> </div>
</div>
<div class="spacer15"> </div>
</div>
I return the paginated results back,but when I click on the page number it takes me to the process.php as the pagination class uses $_SERVER[PHP_SELF]
How can I paginate the results without changing the page url i.e using ajax for the same implementation. I can't make much changes and it would be useful if modifications in this makes it work.(That's why I have tred to add as much code as possible.) Sorry if its too much.
Thanks
EDIT
#Gavin Here is my process.php
<?php session_start();
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
include('processRegion.php');
die();
}
include_once("includes/classes/db_connect.php");
include_once("pagination/paginator.class.php");
$pages = new Paginator();
if(isset($_GET['dataString']))
{
$regionValue = $_GET['dataString'];
//echo "region=".$regionValue;
}
else{
$regionValue = $_POST['dataString'];
}
$reqValue = "'".$regionValue."'";
echo $reqValue;
$arr = explode(",",$reqValue);
//print_r($arr);
$getBack = implode("','",$arr);
$beds = "'".$_POST['beds'];
//echo ($beds);
$arrBeds= explode(",",$beds);
//print_r($arrBeds);
$getBedValue = implode("','",$arrBeds);
$finalBedValue = substr($getBedValue,0,-2);
if(isset($_POST['beds']) && $_POST['beds']!=" ")
{
$cityNameAndRegionName = "cities.city_name like '%".$_SESSION['$cityName']."%' and (suburbs.suburb_name in (".$getBack.")) and (properties_type.bed_type in (".$finalBedValue."))";
}
else
{
$cityNameAndRegionName = "cities.city_name like '%".$_SESSION['$cityName']."%' and (suburbs.suburb_name in (".$getBack."))";
}
$countSql="SELECT count(*) as total from properties inner join cities on properties.city_id=cities.city_id inner join suburbs on properties.suburb_id=suburbs.suburb_id left outer join properties_type on properties.property_id=properties_type.property_id where ".$cityNameAndRegionName." ";
?>
<?php include_once("processRegion.php"); ?>
processRegion.php with HTML
<div class="flt width710" id="">
<div style="float:right" id="toppagesel">
<?php
//Query processed here
?>
</div>
</div>
<div class="spacer15"> </div>
<div><strong>Results for properties for sale</strong> in <?php echo ucfirst($_SESSION['$cityName']) ?>.</div>
<div class="spacer15"> </div>
<div class="width710" id="displayProp">
<?php while($row=mysql_fetch_assoc($result))
{ ?>
<div class="projectlisttiger" id="propertyList">
<div class="spacer5"> </div>
<div class="listnewimg flt">
<a href="p-kolte-patil-cilantro-wagholi-pune.php">
<img src="admin/uploads/<?php echo ($row['property_cover_image']) ?>" width="186" height="125" border="0">
</div>
<div class="listright">
<div style="width:498px; height:42px;" class="flt">
<div class="list-logo flt">
<div class="buildborder"><img width="80" height="36" border="0" align="absmiddle" alt="Kolte Patil" src="admin/uploads/<?php echo $row['builder_logo']?>">
</div>
<div class="tablistname"><?php echo $row['property_name'] ?></div>
</div>
<?php if ($row['property_price_min']!=0) { ?>
<div class="listprice">
<img width="18" height="18" align="absmiddle" src="images/city/rupee_icon.gif"> <?php echo $row['property_price_min'] ?> Lacs - <?php echo $row['property_price_max'] ?> Lacs
</div>
<?php } else { ?>
<div class="listprice">
<img width="18" height="18" align="absmiddle" src="images/city/rupee_icon.gif">Price on Request
</div>
<?php } ?>
</div>
<div class="spacer3"> </div>
<div class="listbox">
<a href="p-kolte-patil-cilantro-wagholi-pune.php"><strong>Address</strong>:<?php echo $row['locality_name'] ?>, <?php echo $row['city_name'] ?><br> <strong>Types</strong>: 2BHK & 3BHK
<br><strong>Sizes:</strong> <?php echo $row['property_size_min'] ?> sqft - <?php echo $row['property_size_max'] ?> sqft </a>
</div>
<div style="margin-left:-3px;" class="flt">
<div style="width:110px;" class="flt"><a style="text-decoration:none;" href="p-kolte-patil-cilantro-wagholi-pune.php"><input type="button" value="View Details" class="detail_project"></a>
</div>
<div style="width:110px;" class="flt"><input type="button" onClick="showEnqForm('2659','Cilantro'); return false;" value="Enquire Now" class="enquire_project"></div>
</div>
<div class="spacer"> </div>
</div>
<div class="spacer15"> </div>
</div>
<?php
}
?>
<div class="spacer15"> </div>
</div>
<div style="float:right" id="toppagesel">
<?php
echo $pages->display_pages();
echo $pages->display_items_per_page();
?>
</div>
As stated in my comments.
You could do the following:
$(document).ready(function()
{
$('.paginate').live('click', function(e)
{
e.preventDefault();
var btnPage = $(this);
$.ajax(
{
url : btnPage.attr('href'),
success : function(resp)
{
// replace current results with new results.
$('#project_section').html(resp);
},
error : function()
{
window.location.href = btnPage.attr('href');
}
});
});
});
The above will replicate you clicking on each of the pagination links.
What I would advise to do next is to separate the PHP code and HTML that generates your "results" list into a separate file.
This way, on the page that displays the results, you can simply use include('path-to-results-file.php'); which will work for non-ajax requests and then you could do:
Process.php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
include('path-to-results-file.php');
die();
}
The above would detect if an ajax request has been made and if so, instead of displaying the whole page including the results, it will simply display only the results and the pagination.
Updated to include a better explanation
Below is a VERY simple example of what I mean.
Current process.php
<?
// currently contains all of the code required
// to query the database etc.
?>
<html>
<head>...</head>
<body>
<!-- header content -->
<table>
<?
// currently contains all of the code required to display
// the results table and pagination links.
?>
</table>
<!-- footer content -->
</body>
</html>
New process.php
<?
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
include('path-to-results-file.php');
die();
}
?>
<html>
<head>...</head>
<body>
<!-- header content -->
<? include('path-to-results-file.php'); ?>
<!-- footer content -->
</body>
</html>
New path-to-results-file.php
<?
// currently contains all of the code required
// to query the database etc.
?>
<table>
<?
// currently contains all of the code required to display
// the results table and pagination links.
?>
</table>
Now... When you go to process.php normally via your browser, or when javascript is disabled. It will simply work the same way it does without Javascript now.
When you go to process.php and then click on one of the pagination links (with javascript enabled), process.php will detect that you are using Ajax and only send back the table of results.