Pagination active link - php

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>";
}

Related

AJAX pagination, update current page

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);

PHP and Ajax pagination. Why GET method always returns empty value?

I'm trying to add pagination, even though the code it seems correct, the page displays only the first 10 results (10 results i want per page). As you can see below, the problem seems to be created in the $_GET method.
Here is the ajax:
function displayAllTopics() {
$.ajax({
url: "requests.php",
type: "GET",
data: {
keyPagination: "displayAllTopics"
},
dataType: "json",
success: function(response) {
$("#topicArea").append(response.response_message);
$("#pagination").append(response.pagination);
}
});
}
Here is the requests.php file:
if(isset($_GET['keyPagination'])) {
if($_GET['keyPagination'] == "displayAllTopics") {
$sql = "SELECT * FROM travel";
$result = mysqli_query($conn, $sql);
$count_topics = mysqli_num_rows($result);
if($count_topics < 1) {
exit('There are no topics yet.');
}
if(isset($_GET['page'])) {
$page = $_GET['page'];
}
else {
$page = 1;
}
//results per page
$results_per_page = 10;
//number of pages
$offset = ($page-1) * $results_per_page;
$number_of_pages = ceil($count_topics / $results_per_page);
$sql_pagination = "SELECT * FROM travel LIMIT $offset, $results_per_page";
$results_pagination = mysqli_query($conn, $sql_pagination);
$response_message = "";
$pagination = "";
while($row = mysqli_fetch_assoc($results_pagination)) {
$user_id = $row['user_id'];
$travel_subject_id = $row['travel_subject_id'];
$travel_subject_date = $row['travel_subject_date'];
$travel_title = $row['travel_subject_title'];
$travel_body = $row['travel_subject_body'];
$travel_comments_count = $row['travel_comments_count'];
$travel_views = $row['travel_subject_views'];
$travel_subject_date_format = date('j M y H:i', strtotime($travel_subject_date));
$sql_user = "SELECT * FROM forum_users WHERE user_id='$user_id'";
$result_user = mysqli_query($conn, $sql_user);
if($row_user = mysqli_fetch_assoc($result_user)) {
$username = $row_user['username'];
$response_message .= "<tr>
<td><a href='travel_subject.php?id=".$travel_subject_id."' onclick='countview(".$travel_subject_id.");'><img src='topic.png' class='img_first'>$travel_title</a></td>
<td><img src='comment.png' class='img_second'><p>$travel_comments_count</p></td>
<td><a href='profile_user.php?id=".$user_id."'><img src='avatar.png' class='img_third'>$username</a></td>
<td><p><img src='views.png' class='img_four'>$travel_views</p></td>
<td><p>$travel_subject_date_format</p></td>
</tr>";
}
}
for ($i = 1; $i <= $number_of_pages; $i++) {
$pagination .= "<a href='forum_index.php?page=".$i."&limit=".$offset."'>$i</a>";
}
$data = array('response_message' => $response_message, 'pagination' => $pagination);
echo json_encode($data);
exit();
}
}
Note: Variable $page is always 1, so it seems that cannot set the $_GET['page'] and as a result from that, the page below displays always the first 10 results. Why is that?
and here is the php file, that i want to display the results:
<div class='display-subjects'>
<table class='display-subjects-table' cols='5'>
<tbody id="topicArea">
</tbody>
</table>
</div>
<div id='pagination'>
<?php
if(isset($_GET['page'])) {
$page = $_GET['page'];
}
else {
$page = 1;
}
?>
</div>
Where is the wrong part? Thanks in advance.
displayAllTopics() needs to take the page number as a parameter, and then pass it in the data option.
function displayAllTopics(pageNum) {
$.ajax({
url: "requests.php",
type: "GET",
data: {
keyPagination: "displayAllTopics",
page: pageNum
},
dataType: "json",
success: function(response) {
$("#topicArea").append(response.response_message);
$("#pagination").append(response.pagination);
}
});
}

Php “preview” and “next”

I have a code what generated a list for number of pages, but I want to replace them with two buttons “preview” and “next”
Code is:
$results = mysqli_query($connecDB,"SELECT COUNT(*) FROM list");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
You'll need a var to know the current page, like:
$page = ($_GET['page']) ? (int)$_GET['page'] : 1;
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
$pagination .= '<li>previous</li>';
for($i = 1; $i<$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '<li>next</li>';
$pagination .= '</ul>';
}
I would use current page with php get but if you are doing where javascript is progressing the pages here is an example.
You will have to modify since I can not see the javascript you are using
You can use jquery
<?php
$results = mysqli_query($connecDB,"SELECT COUNT(*) FROM list");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
?>
<ul class="paginate">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var hash = $(location).attr('hash');
hash = hash.substring(1, hash.length); // Remove #
var pages = <?php echo $pages; ?>;
var content = '';
if(hash > 1 && hash <= pages)
content += '<li>previous</li>';
if(hash >= 1 && hash < pages)
content += '<li>next</li>';
$('.paginate').html(content);
});
</script>
</ul>

pagination class not showing correct amt of pages

the problem with the class is that if i want to display 30 records at a time and i have 60 total records the pagination divs that shows the page numbers only shows page #1 and not page #2. i have tried to figure out how to fix it but i have given up. any help would greatly be apreciated.
this is how i call attributes to the class.
$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
here is the class.
<?php
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($param1=null,$param2=null,$param3=null)
{
$qRows = $this->db->query($this->sql);
$numRows = $this->db->num_rows($qRows);
$numOfPages = ceil($numRows / $this->perPage);
$param = $this->param;
$pageName = $this->pageName;
$string = "";
//set pagination parameters.
if($param1 != null)
{
if(isset($_GET[$param1]))
{
$param1Value = $_GET[$param1];
$string .= "&".$param1."=".$param1Value;
}
}
if($param2 != null)
{
if(isset($_GET[$param2]))
{
$param2Value = $_GET[$param2];
$string .= "&".$param2."=".$param2Value;
}
}
if($param3 != null)
{
if(isset($_GET[$param3]))
{
$param3Value = $_GET[$param3];
$string .= "&".$param3."=".$param3Value;
}
}
print "<div class='pagination'>";
print "<a href='$this->pageName?page=1$string' 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$string'> $i </a>";
}
}
else
{
//print all numbers between current page and first page.
for($i = 1; $i < $param; $i++)
{
print "<a href='$pageName?page=$i$string'> $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$string'> $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$string'> $i </a>";
}
}
// ----------------------------------------------------------------------------
$lastPage = $numOfPages - 1;
print "<a class='next' href='$pageName?page=$lastPage$string'> Last </li>";
print "</div>";
}
function getData()
{
$query = $this->sql;
$this->start = $this->setIndex();
return "$query LIMIT $this->start, $this->perPage";
}
function errors()
{
$query = $this->sql;
print "$query LIMIT $this->start, $this->perPage"."<br/>";
print "this->start ".$this->start."<br/>";
print "this->param ".$this->param."<br/>";
print "this->perPage ".$this->perPage."<br/>";
print "this->setindex() ".$this->setIndex()."<br/>";
}
}
?>
Personally I tend to stray from SELECT * FROM tbl type queries as if you have a large table, it can be slow. Therefore, I run two queries: one to get the total number of records, and one to get the data set I need based on a paging parameter in the URL, e.g. example.com/news.php?page=2.
From there, I can instantiate my own paging class, which is pretty simple:
<?php
class Paging {
private $total;
private $batch;
private $page;
private $prefix;
public function __construct($total=0, $batch=10, $page=1, $url="") {
$this->total = intval($total);
$this->batch = intval($batch);
$this->page = intval($page);
$this->url = $url;
}
public function total_pages() {
return ceil($this->total/$this->batch);
}
public function render() {
$html = "";
// only display paging if we have more than the batch value
if ($this->total > $this->batch) {
$html.= '<p>Go to page:';
for ($i=1; $i <= $this->total_pages()) {
if ($i==$this->page) {
$html.= ' <span class="current">'.$i.'</span>';
}
else {
$html.= ' '.$i.'';
}
}
$html.= '</p>';
}
return $html;
}
}
Then to use:
<?php
// get total number of records
$sql = "SELECT COUNT(*) AS total FROM tbl";
$res = $db->query($sql);
$row = $res->fetch();
$total = $row['total'];
$batch = 20;
$page = intval($_GET['page']);
// instantiate paging class
require_once('paging.class.php');
$paging = new Paging($total, $batch, $page, "mypage.php?page=%s");
// do normal page stuff here...
// render the pagination links
echo $paging->render();
Feel free to use the above code and modify to your needs

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