AJAX pagination, update current page - php

I created a numeric pagination that loads the data via AJAX.
This is the code:
$(document).ready(function(){
load_data(1);
function load_data(page)
{
$.ajax({
url:"pagination2.php",
method:"POST",
data:{page:page},
success:function(data){
$('#load_data').html(data);
}
});
}
$(document).on('click', '.pagination_link', function(event)
{
event.preventDefault();
var page = $(this).attr("id");
load_data(page);
//Now push PAGE to URL
window.history.pushState({page}, `Selected: ${page}`, `${'page=' + page}`)
return event.preventDefault();
});
window.addEventListener('popstate', e => {
var page = $(this).attr("id");
load_data(e.state.page);
console.log('popstate error!');
});
});
The code works, but when I refresh the page the data are loaded again from the first page. test_ajax
Ex: If I click the button that loads the page 2 when I refresh the page the data are displayed from the page 1.
There is a way to remain on the same page even after the page refresh?
pagination2.php
<?php
$rowperpage = 10;
$page = 1;
if($_REQUEST['page'] > 1)
{
$p = (($_REQUEST['page'] - 1) * $rowperpage);
$page = $_REQUEST['page'];
}
else
{
$p = 0;
}
?>
<?php
$visible = $visible ?? true;
$products_count = count_all_products(['visible' => $visible]);
$sql = "SELECT * FROM products ";
$sql .= "WHERE visible = true ";
$sql .= "ORDER BY position ASC ";
$sql .= "LIMIT ".$p.", ".$rowperpage."";
$product_set = find_by_sql($sql);
$product_count = mysqli_num_rows($product_set);
if($product_count == 0) {
echo "<h1>No products</h1>";
}
while($run_product_set = mysqli_fetch_assoc($product_set)) { ?>
<div style="float: left; margin-left: 20px; margin-top: 10px; class="small">
<a href="<?php echo url_for('/show.php?id=' . h(u($run_product_set['id']))); ?>">
<img src="staff/images/<?php echo h($run_product_set['filename']); ?> " width="150">
</a>
<p><?php echo h($run_product_set['prod_name']); ?></p>
</div>
<?php }
mysqli_free_result($product_set);
?>
<section id="pagination">
<?php
$url = url_for('index_all.php');
if($_REQUEST['page'] > 1)
{
$page_nb = $_REQUEST['page'];
}
else
{
$page_nb = 1;
}
$check = $p + $rowperpage;
$prev_page = $page_nb - 1;
$limit = $products_count / $rowperpage;
//echo $limit;
//exit;
$limit = ceil($limit);
$current_page = $page_nb;
if($page_nb > 1) {
//echo "<a href='index_all.php?page=".$prev_page."'>Back</a>";
echo "<span class='pagination_link' style='cursor:pointer;' id='".$prev_page."'>Back</span>";
}
if ( $products_count > $check ) {
for ( $i = max( 1, $page_nb - 5 ); $i <= min( $page_nb + 5, $limit ); $i++ ) {
if ( $current_page == $i ) {
echo "<span class=\"selected\">{$i}</span>";
} else {
echo "<span class='pagination_link' style='cursor:pointer;' id='".$i."'>".$i."</span>";
}
}
}
if ($products_count > $check) {
$next_page = $page_nb + 1;
echo "<span class='pagination_link' style='cursor:pointer;' id='".$next_page."'>Next</span>";
}

When the document is ready you use load_data(1);
That's wrong because if someone refreshes at page 5 it starts anyway from page 1.
Check the current page everytime you refresh.
The code should be something like this:
var url_string = window.location.href;
var url_parts = url_string.split('/');
var piece = url_parts[url_parts.length -1]; //get last part of url (it should be page=n)
var page;
if(piece.substring(0, 5) === 'page=') {
page = parseInt(piece.substr(5));
} else { //if it's the first time you landed in the page you haven't page=n
page = 1;
}
load_data(page);

Related

Pagination active link

I am doing pagination with ajax for table which has some
records for which i have to show active link for each
click.Please do help me with this.
$(document).ready(function()
{
ready_data();
function ready_data(page)
{
$.ajax({
url:"connection.php",
method:"POST",
data:{page:page},
success:function(data){
$('#paginate_record').html(data);
// $('.page_links').removeClass('active');
// $(this).addClass('active');
}
}); }
$(document).on('click', '.page_links ', function(){
var page = $(this).attr("id");
ready_data(page);
});
});
Here is My pagination page
$records_per_page = 2;
$page = '';
if(isset($_POST["page"]))
{
$page = $_POST["page"];
}
else
{
$page = 1;
}
$start_from = ($page - 1)*$records_per_page;
$sql = "SELECT * FROM students LIMIT $start_from,
$records_per_page";
$result = mysqli_query($con,$sql);
$data .= '</table><br /><div align="center">';
$page_sql = "SELECT * FROM students ";
$page_result = mysqli_query($con, $page_sql);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$records_per_page);
for($i=1; $i<=$total_pages; $i++)
{
$data.= "<span class='page_links active'
style='cursor:pointer;margin:10px;padding:1px;border:1px
solid
;'id='".$i."'>".$i."</span>";
}
echo $data;
Now in which i want to show active link for each click.i tried by adding class on ajax succes function also add the active class on span tag but it is applying to all links.so please do help me.
In the last for() loop, you are applying the active class to all the output, you want to apply this only to the current page...
for($i=1; $i<=$total_pages; $i++)
{
$data.= "<span class='page_links";
if ( $i == $page ) {
$data .=" active";
}
$data.= "' style='cursor:pointer;margin:10px;padding:1px;border:1px solid;'id='"
.$i."'>".$i."</span>";
}

Make Pagination using Ajax with Jquery, PHP

This is the first time that I have make (I mean, I try) pagination without page refresh by using Ajax with Jquery, PHP and Mysql.
Problem: Pagination links are not working.
Site content is working.
This is a link to the test page: testpage1
Thank you in advance for your help.
1. Ajax(index.php)
<div id="page">
</div>
<script>
$(document).ready(function(){
load_data();
function load_data(page)
{
$.ajax({
url:"pagination2.php",
method:"POST",
data:{page:page},
success:function(data){
$('#page').html(data);
}
})
}
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
2. PHP (pagination2.php)
if($page_nb > 1) {
echo "<a href='index_all.php?page=".$prev_page."'>Back</a>";
//echo '<span style="cursor:pointer;" onclick="LoadData('.$prev_page.')">Back</span>';
}
if ( $products_count > $check ) {
for ( $i = max( 1, $page_nb - 5 ); $i <= min( $page_nb + 5, $limit ); $i++ ) {
if ( $current_page == $i ) {
echo "<span class=\"selected\">{$i}</span>";
} else {
//echo "{$i}";
echo "<span class='pagination_link' style='cursor:pointer;' id='".$i."'>".$i."</span>";
}
}
}
if ($products_count > $check) {
$next_page = $page_nb + 1;
echo "<a href='index_all.php?page=".$next_page."'>Next</a>";
//echo '<span style="cursor:pointer;" onclick="LoadData('.$next_page.')">Next</span>';
}
3. I think I found a solution
A. Ajax
<script>
$(document).ready(function(){
load_data();
function load_data(page)
{
$.ajax({
url:"pagination2.php",
method:"GET",
data:{page:page},
success:function(data){
$('#page').html(data);
//alert('Successfully called');
},
//error:function(exception){alert('Exeption:'+exception);}
})
}
//load_data(1);
$(document).on('click', '.pagination_link', function(){
var page = $(this).attr("id");
load_data(page);
});
});
</script>
B. Links
if($page_nb > 1) {
//echo "<a href='index_all.php?page=".$prev_page."'>Back</a>";
echo "<span class='pagination_link' style='cursor:pointer;' id='".$prev_page."'>Back</span>";
}
if ( $products_count > $check ) {
for ( $i = max( 1, $page_nb - 5 ); $i <= min( $page_nb + 5, $limit ); $i++ ) {
if ( $current_page == $i ) {
echo "<span class=\"selected\">{$i}</span>";
} else {
//echo "{$i}";
echo "<span class='pagination_link' style='cursor:pointer;' id='".$i."'>".$i."</span>";
}
}
}
if ($products_count > $check) {
$next_page = $page_nb + 1;
//echo "<a href='index_all.php?page=".$next_page."'>Next</a>";
echo "<span class='pagination_link' style='cursor:pointer;' id='".$next_page."'>Next</span>";
}

PHP - pagination count incorrectly

So I have a simple pagination system on my website. But there's a problem with my calculation for the next page. whenever the page is on page 2 the next page is 13 instead of 3. I have tested the calculation and it always comes out with 3 as result. Here is my code:
<?php
$applied_filters = array("parent" => null, "child" => null);
if(isset($_GET['cat'])) {
$applied_filters["parent"] = $_GET['cat'];
if(isset($_GET['sub']))
$applied_filters["child"] = $_GET['sub'];
}
if(isset($_GET['page'])) {
$page = $_GET['page'];
} else {
$page = 1;
}
$products_per_page = 9;
$start_from = ($page-1) * $products_per_page;
$pagination_url = "winkel.php?";
if($applied_filters["parent"] != null) {
$pagination_url .= "cat=" . $applied_filters["parent"];
if($applied_filters["child"] != null) {
$pagination_url .= "&sub=" . $applied_filters["child"] . "&page=";
} else {
$pagination_url .= "&page=";
}
} else {
$pagination_url .= "page=";
}
echo $page . '<br>'; // shows 2
$nextpage = $page + 1; //shows 3
echo $nextpage;
?>
<ul class="pagination">
<?php if($page > 1) { ?>
<li>«
</li>
<?php } ?>
<li class="active"><?= $page ?>
</li>
<?php if($page < $max_pages) { echo $nextpage; // shows 3?>
<li>»
</li>
<?php } ?>
I also have some URL code for the filters on my website:
<?php
// link filters
if(isset($_GET['cat'])) {
if(isset($_GET['cat']) && isset($_GET['sub'])) {
if($_GET['cat'] != "alles")
$result_products = $db->get_by_cat("products", $_GET['cat'], $_GET['sub'], $start_from, $products_per_page);
} else if (isset($_GET['cat'])) {
if($_GET['cat'] != "alles")
$result_products = $db->get_by_cat("products", $_GET['cat'], null, $start_from, $products_per_page);
}
}
if(isset($_POST['clearbrand'])) {
unset($_POST['brandfilter']);
unset($_POST['applybrand']);
}
$filtered_brands = null;
if(isset($_POST['brandfilter'])) $filtered_brands = $_POST['brandfilter'];
// form filters
if(isset($_POST['applybrand'])) {
if(isset($_GET['cat'])) {
$result_products = $db->get_by_checkbox("products", "brand", $_POST['brandfilter'], $_GET);
} else {
$result_products = $db->get_by_checkbox("products", "brand", $_POST['brandfilter']);
}
}
?>
So, does anybody know why my pagination counts from 2 to 13?
Thanks in advance
Your problem is here:
<?php if($page > 1) { ?>
<li>«</li>
<?php } ?>
<li class="active"><?= $page ?></li>
<?php if($page < $max_pages) { echo $nextpage; // shows 3?>
<li>»</li>
<?php } ?>
If $page is greater than 1 (which it is on page 2), you add $page - 1 to the $pagination_url, basically putting a "1" at the end.
Then, in the second if statement, if $page is less than $max_pages, you also add $nextpage (which is 3) to the $pagination_url, putting a "3" after the "1" you added before. Therefore, $pagination_url will now have "13" at the end.
You'll want to change this to:
<?php if($page > 1) { ?>
<li>«</li>
<?php } ?>
<li class="active"><?= $page ?></li>
<?php if($page < $max_pages) { echo $nextpage; // shows 3?>
<li>»</li>
<?php } ?>

javascript include_once- javascript php calling same file duplicating content

I am using ajax to load a php script that shows content based on screen resolution. The script works great, but the url that ajax calls is also called later in the script-- it holds all of the processing information. So, the result is all content is loaded via jquery and then duplicated with php. Example:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'functions/maxresults.php',
type: 'GET',
data: {h: screen.height, w: screen.width}
}).done(function ( data ) {
alert("I am working!");
document.getElementById("container").innerHTML=data;
});
});
</script>
And further down
<?php
include_once("functions/maxresults.php");
?>
<?php
require_once("databasefunctions.php");
?>
<div id="container">
<div id="movieinfo">
<?php include("sidebar.php");?>
<?php
// get the function
include_once ('function.php');
if($_GET['page'])
$page = $_GET['page'];
else
$page = 0;
$maxresults = -1;
if(($_GET['w']) && ($_GET['h'])) {
$w = $_GET['w'];
$h = $_GET['h'];
}
if ($w == 1920) {
$maxresults = 24;
} else if ($w == 1600) {
$maxresults = 21;
} else if ($w == 1440){
$maxresults = 14;
} else if ($w == 1366) {
$maxresults = 21;
} else if ($w == 1024) {
$maxresults = 8;
} else
$maxresults = 6;
echo $maxresults;
$currentpage = $page;
$page = $page*$maxresults;
$numpages = QuickQuery("SELECT COUNT(id) FROM movies WHERE visible=1");
$numpages = mysql_result($numpages, 0);
$numpages = $numpages/$maxresults-1;
$result = GetMoviesByRangeID($page, $maxresults);//Show <maxresults> pages at a time
DisplayResults($result);
?>
</div>
</div>
I cannot remove the php include or the script won't work at all. Would creating an include_once in the jquery work and if so, how do I code it?
PHP is a preprocessor. So, it doesn't matter that you are including it 'later' in the file. Your include_once will be processed and output before the JavaScript is executed.
I looks like the problem is that your include_once script is also outputting the container div. So, when you remove that line it breaks the javascript. Try this instead:
Remove the container div from you maxresults.php file.
Replace the <?php include_once('functions/maxresults.php);> with an empty div with an id of container: <div id="container"></div>
Your JavaScript should work now:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'functions/maxresults.php',
type: 'GET',
data: {h: screen.height, w: screen.width}
}).done(function(resp) {
alert("I am working!");
$("#container").html(resp);
});
});
</script>
And further down
<div =id="container"></div>
maxresults.php
<?php
require_once("databasefunctions.php");
?>
<div id="movieinfo">
<?php include("sidebar.php");?>
<?php
// get the function
include_once ('function.php');
if($_GET['page'])
$page = $_GET['page'];
else
$page = 0;
$maxresults = -1;
if(($_GET['w']) && ($_GET['h'])) {
$w = $_GET['w'];
$h = $_GET['h'];
}
if ($w == 1920) {
$maxresults = 24;
} else if ($w == 1600) {
$maxresults = 21;
} else if ($w == 1440){
$maxresults = 14;
} else if ($w == 1366) {
$maxresults = 21;
} else if ($w == 1024) {
$maxresults = 8;
} else
$maxresults = 6;
echo $maxresults;
$currentpage = $page;
$page = $page*$maxresults;
$numpages = QuickQuery("SELECT COUNT(id) FROM movies WHERE visible=1");
$numpages = mysql_result($numpages, 0);
$numpages = $numpages/$maxresults-1;
$result = GetMoviesByRangeID($page, $maxresults);//Show <maxresults> pages at a time
DisplayResults($result);
?>
</div>

Pagination Class calculates incorrectly

ive written a pagination class and it looks like its not outputting the correct amount of rows. i have a table full of 51 records and instead it shows only 30 records and as for the pages it shows only page 1 where it should show page 1 and 2. the pages are viewed by going to page=1 as a browser param. when i try to view page=2 i see the rest of the records. here is the class.
include_once("class.db.php");
class Pagination {
var $param;
var $perPage;
var $adjacents;
var $start;
var $sql;
var $pageName;
function __construct() {
$this->db = new MysqlDB;
$this->db->connect();
}
function setParam() {
if(isset($_GET['page']) && is_numeric($_GET['page']) && ($_GET['page'] > 0)) {
$this->param = $_GET['page'];
} else {
$this->param = 1;
}
}
function setIndex() {
$this->setParam();
return $this->start = ($this->param * $this->perPage) - $this->perPage;
}
function showPagination() {
$qRows = $this->db->query($this->sql);
$numRows = $this->db->num_rows($qRows);
$numOfPages = ceil($numRows / $this->perPage);
$param = $this->param;
$pageName = $this->pageName;
print "<div class='pagination'>";
print "<a href='$this->pageName?page=1' class='previous-off'> First </a>";
// ----------------------------------------------------------------------------
// PRINT ALL PAGES TO THE LEFT //
if(($param - $this->adjacents) > 1) {
print "<span>...</span>";
$lowerLimit = $param - $this->adjacents;
//print all on left side.
for($i = $lowerLimit; $i< $param; $i++) {
print "<a href='$pageName?page=$param = $i'> $i </a>";
}
} else {
//print all numbers between current page and first page.
for($i = 1; $i < $param; $i++) {
print "<a href='$pageName?page=$i'> $i </a>";
}
}
// ----------------------------------------------------------------------------
//print current page
if(($param != 0) && ($param != $numOfPages)) {
print "<span class='current'>$param</span>";
}
// ----------------------------------------------------------------------------
//PRINT ALL PAGES TO THE RIGHT
if(($param + $this->adjacents) < $numOfPages) {
$upperLimit = $param + $this->adjacents;
for($i=($param + 1); $i<=$upperLimit; $i++) {
print "<a href='$pageName?page=$i'> $i </a>";
}
print "<span>...</span>";
} else {
//print all page numbers if out of padded range
for($i = $param + 1; $i<$numOfPages; $i++ ) {
print "<a href='$pageName?page=$i'> $i </a>";
}
}
// ----------------------------------------------------------------------------
$lastPage = $numOfPages - 1;
print "<a class='next' href='$pageName?page=$lastPage'> Last </li>";
print "</div>";
}
function getData() {
$query = $this->sql;
$this->start = $this->setIndex();
return "$query LIMIT $this->start, $this->perPage";
}
}
this is how i use the class:
$db = new MysqlDB;
$paginate = new Pagination;
$paginate->pageName = "index.php"; //sets the page to use
$paginate->perPage = 10; //show num of records per page
$paginate->adjacents = 3; //current page adjacent to
$paginate->sql = "select * from tbl_products"; //the main query
$query = $db->query($paginate->getData());
while($row = mysql_fetch_object($query)) {
print $row->pName."<br/>";
}
$paginate->showPagination(); //shows the pagination div
In function setIndex you have to write:
return $this->start = (($this->param - 1) * $this->perPage) - $this->perPage;
because a query should look like:
for page 1: SELECT ... LIMIT 0,[nr_of_pages]
for page 2: SELECT ... LIMIT [nr_of_pages]*1,[nr_of_pages]
...

Categories