PHP: paging with Ajax not working correctly - php

I'm fetching records from a database and displaying them in gruops using php and ajax.
The script below (found somewhere) is almost working, but it seems that when you are on the first page and clicking "Next" you are taken to the LAST page.
Only when clicking the numbers individually, the paging is correct.
I can provide a test link in a PM if needed.
index.php:
<script>
$(document).ready(function() {
$("#results" ).load( "pages.php"); //load initial records
//executes code below when user click on pagination links
$("#results").on( "click", ".pagination a", function (e){
e.preventDefault();
var page = $(this).attr("data-page"); //get page number from link
$("#results").load("pages.php",{"page":page}, function(){ //get content from PHP page
});
});
});
</script>
<div id="results"></div>
pages.php:
<?php
// continue only if $_POST is set and it is a Ajax request
if (isset($_POST) && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
include (realpath(__DIR__ . '/../db.php'));
// Get page number from Ajax POST
if (isset($_POST["page"])) {
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH); //filter number
if (!is_numeric($page_number)) {
die('Invalid page number!');
}
}
else {
$page_number = 1; //if there's no page number, set it to 1
}
// get total number of records from database for pagination
$sql = "SELECT * FROM " . $DBtable . " ORDER BY dates DESC";
$rs = $conn->query($sql);
if ($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
}
else {
$get_total_rows = $rs->fetch_row(); //hold total records in variable
}
// break records into pages
$total_pages = ceil($get_total_rows[0] / $item_per_page);
// get starting position to fetch the records
$page_position = (($page_number - 1) * $item_per_page);
// Limit our results within a specified range.
$rs = $conn->prepare("SELECT id, title, description, dates, clicks FROM " . $DBtable . " ORDER BY dates DESC LIMIT $page_position, $item_per_page");
$rs->execute(); //Execute prepared Query
$rs->bind_result($id, $title, $description, $dates, $clicks); //bind variables to prepared statement
echo '<ul class="contents">';
while($rs->fetch()){ //fetch values
echo '<li>';
echo $id. '. <strong>' .$name.'</strong> — '.$description;
echo '</li>';
}
echo '</ul>';
echo '<div align="center">';
/* We call the pagination function here to generate Pagination link for us. */
echo paginate_function($item_per_page, $page_number, $get_total_rows[0], $total_pages);
echo '</div>';
exit;
}
// ############### pagination function #########################################
function paginate_function($item_per_page, $current_page, $total_records, $total_pages) {
$pagination = '';
if ($total_pages > 0 && $total_pages != 1 && $current_page <= $total_pages) { //verify total pages and current page number
$pagination.= '<ul class="pagination">';
$right_links = $current_page + 3;
$previous = $current_page - 3; //previous link
$next = $current_page + 1; //next link
$first_link = true; //boolean var to decide our first link
if ($current_page > 1) {
$previous_link = ($previous == 0) ? 1 : $previous;
$pagination.= '<li class="class="page-item" first"><a class="page-link" href="#" data-page="1" title="First">«</a></li>'; //first link
$pagination.= '<li class="page-item"><a class="page-link" href="#" data-page="' . $previous_link . '" title="Prev"><</a></li>'; //previous link
for ($i = ($current_page - 2); $i < $current_page; $i++) { //Create left-hand side links
if ($i > 0) {
$pagination.= '<li class="page-item"><a class="page-link" href="#" data-page="' . $i . '" title="Page' . $i . '">' . $i . '</a></li>';
}
}
//set first link to false
$first_link = false;
}
if ($first_link) { //if current active page is first link
$pagination.= '<li class="page-item active first"><a class="page-link" href="#">' . $current_page . '<span class="sr-only">(current)</span></a></li>';
}
elseif ($current_page == $total_pages) { //if it's the last active link
$pagination.= '<li class="page-item active last"><a class="page-link" href="#">' . $current_page . '<span class="sr-only">(current)</span></a></li>';
}
else { //regular current link
$pagination.= '<li class="page-item active"><a class="page-link" href="#">' . $current_page . '<span class="sr-only">(current)</span></a></li>';
}
for ($i = $current_page + 1; $i < $right_links; $i++) { //create right-hand side links
if ($i <= $total_pages) {
$pagination.= '<li class="page-item"><a class="page-link" href="#" data-page="' . $i . '" title="Page ' . $i . '">' . $i . '</a></li>';
}
}
if ($current_page < $total_pages) {
$next_link = ($i > $total_pages) ? $total_pages : $i;
$pagination.= '<li class="page-item"><a class="page-link" href="#" data-page="' . $next_link . '" title="Next">></a></li>'; //next link
$pagination.= '<li class="page-item last"><a class="page-link" href="#" data-page="' . $total_pages . '" title="Last">»</a></li>'; //last link
}
$pagination.= '</ul>';
}
//return pagination links
return $pagination;
}
// Free memory
$rs->free();
// Close connection
$conn->close();
?>
This is the current parsed html of the pager:
<ul class="pagination">
<li class="page-item active first"><a class="page-link" href="#">1<span class="sr-only">(current)</span></a></li>
<li class="page-item"><a class="page-link" href="#" data-page="2" title="Page 2">2</a></li>
<li class="page-item"><a class="page-link" href="#" data-page="3" title="Page 3">3</a></li>
<li class="page-item"><a class="page-link" href="#" data-page="4" title="Next">></a></li>
<li class="page-item last"><a class="page-link" href="#" data-page="4" title="Last">»</a></li>
</ul>

just try like below in your paginate_function()
$next_link = ($i > $total_pages) ? $total_pages : $i;
to
$next_link = (($current_page + 1) > $total_pages) ? $total_pages : $current_page + 1;

Please make changes in paginate_function function as below
if ($current_page < $total_pages) {
$next_link = ($i > $total_pages) ? $total_pages : $i;
$pagination.= '<li class="page-item"><a class="page-link" href="#" data-page="' . $next_link . '" title="Next">></a></li>'; //next link
$pagination.= '<li class="page-item last"><a class="page-link" href="#" data-page="' . $total_pages . '" title="Last">»</a></li>'; //last link
}
Change this to
if ($current_page < $total_pages) {
$next_link = ($i > $total_pages) ? $total_pages : $next;
$pagination.= '<li class="page-item"><a class="page-link" href="#" data-page="' . $next_link . '" title="Next">></a></li>'; //next link
$pagination.= '<li class="page-item last"><a class="page-link" href="#" data-page="' . $total_pages . '" title="Last">»</a></li>'; //last link
}

Related

jQuery selector to capture class inside php if statement

I'd like to make a selector to capture click events on code below :
index.php :
<ul class="pagination">
<?php
if ($page > 1) {
$link = $page - 1;
$prev = '<li class="page-item"><a class="page-link" href="javascript:void(0);" id="'.$link.','.$record_per_page.'">Previous</a></li>';
}else{
$prev = '<li class="page-item"><a class="page-link" href="javascript:void(0);">Previous</a></li>';
}
$num = '';
for($i = 1; $i<=$total_pages ; $i++){
if($i == $page){
$num .= '<li class="page-item"><a class="page-link" href="javascript:void(0);" id="'.$i.'">'.$i.'</a></li>';
}else{
$num .= '<li class="page-item"><a class="page-link" href="javascript:void(0);" id="'.$i.','.$record_per_page.'">'.$i.'</a></li>';
}
}
if ($page < $total_pages) {
$link = $page + 1;
$next = '<li class="page-item"><a class="page-link" href="javascript:void(0);" id="'.$link.','.$record_per_page.'">Next</a></li>';
}else{
$next = '<li class="page-item"><a class="page-link" href="javascript:void(0);">Next</a></li>';
}
echo $prev.$num.$next;
?>
</ul>
script.js :
$(document).on('click','.page-link',function () {
console.log('aaaaaa');
});
I already tried codes above, but it doesn't work, the console.log never showed up, is there any problem with my php code or jquery code ?
Thanks to all , and especially for Ritesh Khandekar, who gave me this code to solve my problem :
$(document).on('click','ul li .page-item',function() { console.log('aaaaaa'); });
I don't know why using page-item instead of page-link, but it workssss !!!!

pagination using post id

Am new to php, i am try to use pagenation , where i post a unique id to a page then use that to load content with the respective id then pagenate all the content with that respective id.
Here below is what have been trying
<?php
if (isset($_GET["post"]))
{
$page = $_GET["post"];
} else
{
$page = 1;
};
$limit = 2;
$total_records = $pagination;
$total_pages = ceil($total_records/$limit);
$lastpage = ceil($total_pages/$limit);
$page != 0;
$prev = $page - 1; //previous page is page - 1
$next = $page + 1; //next page is page + 1
//lastpage is = total pages / items per page, rounded up.
if($prev == 0)
$prev = 1;
$next <= $lastpage;
//if no page var is given, default to 1.
$pagLink = "<ul class='pagination pagination-circle' class='justify- content-center'>";
$pagLink .= "<li class='page-item active'>
<a class='page-link black' href='home.php?post=".$prev."' aria-label='Back'>
<span aria-hidden='true'>«</span>
<span class='sr-only'>Next</span>
</a>
</li>";
for ($i=1; $i<=$total_pages; $i++) {
$pagLink .= "<li class='page-item active'><a class='page-link' href='home.php?post=".$i."'>".$i."</a></li> ";
};
$pagLink .= "<li class='page-item pg-red active'>
<a class='page-link black' href='home.php?post=".$next."' aria-label='Next'>
<span aria-hidden='true'>»</span>
<span class='sr-only'>Next</span>
</a>
</li>";
echo $pagLink . "</ul>";
?>
Here is how i want to pagenate contents per id
enter image description here

pagination next and previous button

hello guys can you help me out ?
i have a problem in pagination
i just want to disable the next and previous
button in my pagination if it is
no item left
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "final";
$con= mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysqli_select_db($con, "final") or die ("no database");
$pagination_sql = "SELECT * FROM `ongoing` WHERE approved='approve'";
$run_pagination = mysqli_query($con, $pagination_sql);
$count = mysqli_num_rows($run_pagination);
$total_pages = ceil($count/$per_page);
echo "<ul class='pagination'>";
echo "<li class='page-item'><a class='page-link' href='ongoing.php?page=".($page-1)."' class='button'>
<span aria-hidden='true'>«</span>
<span class='sr-only'>Previous</span>
</a></li>";
for($i=1;$i<=$total_pages;$i++){
echo'<li><a class="page-link" href="ongoing.php?page='.$i.'">'.$i.'</a></li>';
};
echo "<li class='page-item'><a class='page-link' href='ongoing.php?page=".($page+1)."' class='button'>
<span aria-hidden='true'>»</span>
<span class='sr-only'>Next</span>
</a></li>";
echo "</ul>";
?>
and here's the condition of per page
$per_page = 10;
if(isset($_GET['page'])){
$page = $_GET['page'];
}else{
$page= 1;
}
$start_from = ($page-1) * $per_page;
I think you just need to adjust your code as below:
echo "<ul class='pagination'>";
if($page == 1) {
$disable_prev = 'disabled';
$prev_url = "javascript:void(0);";
} else {
$disable_prev = '';
$prev_url = "ongoing.php?page=".($page-1);
}
echo "<li class='page-item ".$disable_prev."'><a class='page-link' href='".$prev_url."' class='button'>
<span aria-hidden='true'>«</span>
<span class='sr-only'>Previous</span>
</a></li>";
for($i=1;$i<=$total_pages;$i++){
echo'<li><a class="page-link" href="ongoing.php?page='.$i.'">'.$i.'</a></li>';
};
if($page+1 == $total_pages) {
$disable_next = '';
$next_url = "ongoing.php?page=".($page+1);
} else {
$disable_next = 'disabled';
$next_url = "javascript:void(0);";
}
echo "<li class='page-item ".$disable_next."'><a class='page-link' href='".$next_url."' class='button'>
<span aria-hidden='true'>»</span>
<span class='sr-only'>Next</span>
</a></li>";
echo "</ul>";
Then you can also add some CSS to make disabled li little visible or faded than other
Try:
if($i != NULL){ //NULL or Empty
//Code here
}

How can i detect category page on Joomla?

I want to detect virtuemart category page in mod_breadcrumbs.
Breadcrumbs is loading all page and i just wanted write a message in category page.
My breadcrumbs code:
<div class="breadcrumbs<?php echo $moduleclass_sfx; ?>">
<?php
echo '<ul>';
for ($i = 0; $i < $count; $i ++) {
// If not the last item in the breadcrumbs add the separator
if ($i < $count -1) {
if (!empty($list[$i]->link)) echo '<li>'.$list[$i]->name.'</li>';
else echo '<li class="pathway">' . $list[$i]->name . '</li>';
if($i < $count -2) echo ' <li class="pathway separator">></li> ';
} else if ($params->get('showLast', 1)) { // when $i == $count -1 and 'showLast' is true
if($i > 0) echo ' <li class="pathway separator">></li> ';
echo '<li class="pathway">' . $list[$i]->name . '</li>';
}
}
echo '</ul>';
?>
</div>
Here's how you can check if you're on a category view:
$appInput = Jfactory::getApplication()->input;
if($appInput->getCmd('option')=='com_content' && $appInput->getCmd('view')=='category' ){
//add your code here
}

Using Pagination with Mysql Queries

I am unable to maintain a GET variable with this pagination script. Was hoping you all could help.
I am using a GET function so the user can choose which categories are displayed. I'm using a pagination script I found online and I am now confronted with this issue, when I choose "page 2" $dynCat no longer is parsed in the URL because the pagination script creates a new URL and uses GET also.
Could someone help me out with using pagination with a variable query? Thank you.
ERROR Notice: Undefined index: dynCat ----/dynCat.php on line 32
I understand why it is undefined, I just don't know how to integrate and maintain the user's Query (i.e. GET variable from URL) with the pagination script. Thanks again.
Page1 index.php (User Selects option)
<?php
//Generate and list Categories include "storescripts/connect_to_mysql.php";
$dynCat = "";
$data = mysql_query("SELECT category, id FROM products GROUP BY category") or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
$listcategory = $info["category"];
$dynCat .=
'
<li>
<a href="dynCat.php?dynCat='.$listcategory.'" > '.$listcategory.' </a>
</li>
';
}
mysql_close();
?>
<?php echo $dynCat; ?>
Page2 dynCat.php (User Views Selection with Pagination)
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php
//Generate and list Categories
include "storescripts/connect_to_mysql.php";
$dynGallery = "";
$dynCat = "";
$data = mysql_query("SELECT category, id FROM products GROUP BY category") or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
$listcategory = $info["category"];
$dynCat .=
'
<li>
<a href="dynCat.php?dynCat='.$listcategory.'" > '.$listcategory.' </a>
</li>
';
}
mysql_close();
?>
<?php
//Query User Selection & Pagination
include('storescripts/connect_to_mysql.php');
$cat = mysql_escape_string($_GET['dynCat']);
$tableName="products";
$targetpage = "dynCat.php";
$limit = 3;
$query = "SELECT COUNT(*) as num FROM $tableName WHERE category = '$cat'";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages['num'];
$stages = 3;
$page = mysql_escape_string(isset($_GET['page'])) ? mysql_escape_string($_GET['page']) : 0;
if($page){
$start = ($page - 1) * $limit;
}else{
$start = 0;
}
// Get category Data and Images
$query1 = "SELECT * FROM $tableName WHERE category = '$cat' ORDER BY views DESC LIMIT $start, $limit";
$result = mysql_query($query1);
// Initial page num setup
if ($page == 0){$page = 1;}
$prev = $page - 1;
$next = $page + 1;
$lastpage = ceil($total_pages/$limit);
$LastPagem1 = $lastpage - 1;
$paginate = '';
if($lastpage > 1)
{
$paginate .= "<div class='paginate'>";
// Previous
if ($page > 1){
$paginate.= "<a href='$targetpage?page=$prev#gallery'>previous</a>";
}else{
$paginate.= "<span class='disabled'>previous</span>"; }
// Pages
if ($lastpage < 7 + ($stages * 2)) // Not enough pages to breaking it up
{
for ($counter = 1; $counter <= $lastpage; $counter++)
{
if ($counter == $page){
$paginate.= "<span class='current'>$counter</span>";
}else{
$paginate.= "<a href='$targetpage?page=$counter#gallery'>$counter</a>";}
}
}
elseif($lastpage > 5 + ($stages * 2)) // Enough pages to hide a few?
{
// Beginning only hide later pages
if($page < 1 + ($stages * 2))
{
for ($counter = 1; $counter < 4 + ($stages * 2); $counter++)
{
if ($counter == $page){
$paginate.= "<span class='current'>$counter</span>";
}else{
$paginate.= "<a href='$targetpage?page=$counter#gallery'>$counter</a>";}
}
$paginate.= "...";
$paginate.= "<a href='$targetpage?page=$LastPagem1#gallery'>$LastPagem1</a>";
$paginate.= "<a href='$targetpage?page=$lastpage#gallery'>$lastpage</a>";
}
// Middle hide some front and some back
elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2))
{
$paginate.= "<a href='$targetpage?page=1#gallery'>1</a>";
$paginate.= "<a href='$targetpage?page=2#gallery'>2</a>";
$paginate.= "...";
for ($counter = $page - $stages; $counter <= $page + $stages; $counter++)
{
if ($counter == $page){
$paginate.= "<span class='current'>$counter</span>";
}else{
$paginate.= "<a href='$targetpage?page=$counter#gallery'>$counter</a>";}
}
$paginate.= "...";
$paginate.= "<a href='$targetpage?page=$LastPagem1#gallery'>$LastPagem1</a>";
$paginate.= "<a href='$targetpage?page=$lastpage#gallery'>$lastpage</a>";
}
// End only hide early pages
else
{
$paginate.= "<a href='$targetpage?page=1#gallery'>1</a>";
$paginate.= "<a href='$targetpage?page=2#gallery'>2</a>";
$paginate.= "...";
for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++)
{
if ($counter == $page){
$paginate.= "<span class='current'>$counter</span>";
}else{
$paginate.= "<a href='$targetpage?page=$counter#gallery'>$counter</a>";}
}
}
}
// Next
if ($page < $counter - 1){
$paginate.= "<a href='$targetpage?page=$next#gallery'>next</a>";
}else{
$paginate.= "<span class='disabled'>next</span>";
}
$paginate.= "</div>";
}
mysql_close();
?>
<?php
$productCount = mysql_num_rows($result); // count the output amount
while($row = mysql_fetch_array($result))
{
$id = $row["id"];
$product_name = $row["product_name"];
$price = $row["price"];
$category = $row["category"];
$subcategory = $row["subcategory"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
$dynGallery .=
'
<div>
<li>
<a href="product.php?id=' . $id . '#gallery">
<img style="border:#FFF 1px solid;" src="inventory_images/' . $id . '.jpg" alt="' . $product_name . '" width="180" height="255" border="1" style="opacity: 0;/></a>
<h4> <a name= ' . $id . ' id= ' . $id . ' value= ' . $id . ' href="product.php?id= ' . $id . '#gallery"> ' . $product_name . ' </a> </h4>
<p>'. $category .'</p>
<p>'. $subcategory .'</p>
<span> $' . $price . '</span>
</li>
</div>
';
}
?>
<!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">
<body>
<?php include ("../header.php");?>
<?php include ("../menu.php");?>
<a id="shop"></a>
<div class="body">
<div class="sidebar">
<div class="first">
<h2>Dora Designs</h2>
<!-- Dynamic Categories -->
<ul>
<?php echo $dynCat; ?>
</ul>
</div>
</div>
<div class="content">
<div class="figure">
<img src="/images/galleryholder.png" alt=""/>
</div>
<div class="products">
<div class="paging" align = "center">
<a id="gallery"></a>
<? echo $paginate;?>
<? echo '</br>'. $cat;?>
<? echo '</br>'. $total_pages.' Results'; ?>
</div>
<ul>
<?php echo $dynGallery; ?>
</ul>
I hate to dump this much code in the post but I am really at a loss and have never used Pagination before. Any help will be greatly appreciated.
change ever instance of
$targetpage?page=
to
$targetpage?dynCat=$cat&page=
you want 2 copies of $cat one for the db requires escaping with mysql_escape_string() the other for the url with urlencode()
replace the line
$cat = mysql_escape_string($_GET['dynCat']);
with
$cat=urldecode($_GET['dynCat']); //from the url, raw value to display
$cat_mysql = mysql_escape_string($cat); //use in mysql queries
$cat_url=urlencode($cat); //use in the url
then
$targetpage?dynCat=$cat&page=
will now be
$targetpage?dynCat=$cat_url&page=
Try adding dynCat=$cat to all of your links that look like this - <a href='$targetpage?page=...
<a href='$targetpage?dynCat=$capage=...
on a quick search there are approx. 14 of them to change.

Categories