Make Pagination using Ajax with Jquery, PHP - 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>";
}

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

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

muliplte counter timers not working on single page

i have multiple timers on a page but the code doesn't seem to work for it.
in the code below the timer for each post gets started with onload function which calls the jquery code
the code i used i got it from another thread here i just modified it to work with onload for each span but it doesn't work then
<?php
$i=0;
$timeleft="05:00:30";
while ( $loop->have_posts() ) : $loop->the_post();
?>
<span id="countdown<?php echo $i; ?>" onload="start_timer(<?php echo $i; ?>,<?php echo $timeleft; ?>)"> <?php echo $timeleft; ?> </span>
<?php $i++;endwhile;wp_reset_postdata(); ?>
<script type="text/javascript">
function start_timer(num,time){
$(document).ready(function() {
parts = time.split(':'),
hours = +parts[0],
minutes = +parts[1],
seconds = +parts[2],
span = $('#countdown'+num);
function correctNum(num) {
return (num<10)? ("0"+num):num;
}
var timer = setInterval(function(){
seconds--;
if(seconds == -1) {
seconds = 59;
minutes--;
if(minutes == -1) {
minutes = 59;
hours--;
if(hours==-1) {
alert("timer finished");
clearInterval(timer);
return;
}
}
}
span.text(correctNum(hours) + ":" + correctNum(minutes) + ":" + correctNum(seconds));
}, 1000);
});
}
</script>
onload is only supported on the following elements
you can do something like this:
<?php
while ( $loop->have_posts() ) : $loop->the_post();
?>
<span id="countdown<?php echo $i; ?>"> <?php echo $timeleft; ?> </span>
<script>start_timer(<?php echo $i; ?>,'<?php echo $timeleft; ?>');</script>
<?php $i++;endwhile;wp_reset_postdata(); ?>
Edit:
change you javascript to this:
<script type="text/javascript">
function myFormat(num){
return (num < 10)? ("0"+num): num;
}
function StartTimer(num, time){
this.parts = time.split(':');
this.hours = this.parts[0];
this.minutes = this.parts[1];
this.seconds = this.parts[2];
this.span = $('#countdown' + num);
}
StartTimer.prototype.myTimer = function(){
var s = this.seconds;
var m = this.minutes;
var h = this.hours;
var sp = this.span;
var t = setInterval(function(){
s--;
if(s == -1) {
s = 59;
m--;
if(m == -1) {
m = 59;
h--;
if(h == -1) {
alert("timer finished");
clearInterval(t);
return;
}
}
}
//console.log();
//console.log();
//console.log();
sp.text(h + ":" + myFormat(m) + ":" + myFormat(s));
}, 1000);
};
</script>
and your while loop:
<?php
while ( $loop->have_posts() ) : $loop->the_post();
?>
<span id="countdown<?php echo $i; ?>"> <?php echo $timeleft; ?> </span>
<script>new StartTimer(<?php echo $i; ?>,'<?php echo $timeleft; ?>').myTimer();</script>
<?php $i++;endwhile;wp_reset_postdata(); ?>
you can also check it in JSFiddle here

ajax php pagination wont show active page

I am working on a php ajax pagination.
The problem is that it wont ad the class="highlightActivePage" proper.
If I click on 1 - 2 - 3 , it works fine and highlight the number 3 if im on page 3.
But soon as I click on page 4 it highlights page 5 instead, etc.
Not sure if my for loop is wrong, but here us my code:
if (paginationHTML == "")
{
paginationHTML += "<ul>";
if (adResultsData.show_first_text == 1)
{
paginationHTML += "<li><a href='#' onclick='fetchResults(1);'>First</a></li>";
}
if (adResultsData.show_previous_text == 1)
{
paginationHTML += "<li><a href='#' onclick='fetchResults(" + (adResultsData.current_page - 1) + ");'>Prev</a></li>";
}
for (var i = 0; i < adResultsData.pages.length; i++)
{
if (adResultsData.current_page == (i + 1))
{
paginationHTML += "<li><a href='#' class='highlightActivePage' onclick='fetchResults(" + adResultsData.pages[i] + ");'>" + adResultsData.pages[i] + "</a></li>";
}
else
{
paginationHTML += "<li><a href='#' onclick='fetchResults(" + adResultsData.pages[i] + ");'>" + adResultsData.pages[i] + "</a></li>";
}
}
if (adResultsData.show_next_text == 1)
{
paginationHTML += "<li><a href='#' onclick='fetchResults(" + (adResultsData.current_page + 1) + ");'>Next</a></li>";
}
if (adResultsData.show_last_text == 1)
{
paginationHTML += "<li><a href='#' onclick='fetchResults(" + adResultsData.number_of_pages + ");'>last</a></li>";
}
paginationHTML += "</ul>";
paginationHTML += pageSpan.innerHTML = "<br>Page " + adResultsData.current_page + " of " + adResultsData.number_of_pages;
}
php
$numberOfPages = $results['pages'];
$currentPage = $results['currentPage'];
if ($currentPage != 1 && $currentPage != 2)
{$showFirst = 1;}
else $showFirst = 0;
if ($currentPage != 1)
{$showPrevious = 1;}
else $showPrevious = 0;
if ($currentPage != $numberOfPages)
{$showNext = 1;}
else $showNext = 0;
if ($currentPage != $numberOfPages && $currentPage != ($numberOfPages - 1))
{$showLast = 1;}
else $showLast = 0;
if ($currentPage <= 5 && $numberOfPages <= 5 || $numberOfPages <= 5)
{$startingPage = 1;}
else if ($currentPage == 1 || $currentPage == 2)
{$startingPage = 1;}
else
{$startingPage = $currentPage - 2;}
$pageNumbers = [];
for ($i = $startingPage; $i < ($startingPage + 5) && $i <= $numberOfPages; $i++)
{
$pageNumbers[] = $i;
}
$pagesString = implode(", ", $pageNumbers);
$listingsString = implode(", ", $listingsArray);
$jsonString = <<< END
{
"resultsTotal" : $numberOfResults,
"listings" : [$listingsString],
"number_of_pages" : $numberOfPages,
"current_page" : $currentPage,
Thanks!

php jquery pagination expanding without moving to the next page

Im working on a codeigniter project which takes results and adds it to the page with pagination.
The problem that im having is,
the page shows all the page numbers but the first page always seems empty. When i move to the second page it shows the first page results along with the second page results. Even if i move to the first page again its empty.
when i move further, all the results seems to be stacked rather than paginating.
so first page 0 results. the second page shows 30, 3rd page shows 45 results.
below is my script
<script type="text/javascript">
$(document).ready(function(){
function loading_show(){
$('#loading').html("<img src='<?php echo $url?>images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
$.ajax
({
type: "POST",
url: "<?php echo base_url()?>index.php/controls/ajaxload",
data: "page="+page,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1);
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
$('#go_btn').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter Number '+no_of_pages);
$('.goto').val("").focus();
return false;
}
});
});
</script>
php code
function ajaxload()
{
if($_POST['page'])
{
$page = $_POST['page'];
$cur_page = $page;
$page -= 1;
$per_page = 15;
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;
$city ='London';
$this->load->model('control_model');
$query_pag_datas = $this->control_model->data_for_pagination($start, $per_page,$city);
$msg = "";
foreach ($query_pag_datas as $single):
$htmlmsg = htmlentities($single['Description']);
$msg .= "<li><b>" . $single['offID'] . "</b> " . $htmlmsg . "</li>";
endforeach;
$msg = "<div class='data'><ul>" . $msg . "</ul></div>";
$count = $this->control_model->count_pages($city);
$no_of_paginations = ceil($count / $per_page);
if ($cur_page >= 7) {
$start_loop = $cur_page - 3;
if ($no_of_paginations > $cur_page + 3)
$end_loop = $cur_page + 3;
else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
$start_loop = $no_of_paginations - 6;
$end_loop = $no_of_paginations;
} else {
$end_loop = $no_of_paginations;
}
} else {
$start_loop = 1;
if ($no_of_paginations > 7)
$end_loop = 7;
else
$end_loop = $no_of_paginations;
}
$msg .= "<div class='pagination'><ul>";
if ($first_btn && $cur_page > 1) {
$msg .= "<li p='1' class='active'>First</li>";
} else if ($first_btn) {
$msg .= "<li p='1' class='inactive'>First</li>";
}
if ($previous_btn && $cur_page > 1) {
$pre = $cur_page - 1;
$msg .= "<li p='$pre' class='active'>Previous</li>";
} else if ($previous_btn) {
$msg .= "<li class='inactive'>Previous</li>";
}
for ($i = $start_loop; $i <= $end_loop; $i++) {
if ($cur_page == $i)
$msg .= "<li p='$i' style='color:#fff;background-color:#006699;' class='active'>{$i}</li>";
else
$msg .= "<li p='$i' class='active'>{$i}</li>";
}
if ($next_btn && $cur_page < $no_of_paginations) {
$nex = $cur_page + 1;
$msg .= "<li p='$nex' class='active'>Next</li>";
} else if ($next_btn) {
$msg .= "<li class='inactive'>Next</li>";
}
if ($last_btn && $cur_page < $no_of_paginations) {
$msg .= "<li p='$no_of_paginations' class='active'>Last</li>";
} else if ($last_btn) {
$msg .= "<li p='$no_of_paginations' class='inactive'>Last</li>";
}
$goto = "<input type='text' class='goto' size='1' style='margin-top:-1px;margin-left:60px;'/><input type='button' id='go_btn' class='go_button' value='Go'/>";
$total_string = "<span class='total' a='$no_of_paginations'>Page <b>" . $cur_page . "</b> of <b>$no_of_paginations</b></span>";
$msg = $msg . "</ul>" . $goto . $total_string . "</div>";
echo $msg;
}
}
any help will be appreciated.
So if the page you are posting is 1, this is what you get:
Page 1:
$page = $_POST['page'];//let's say we're posting page 1, so $page === 1
...
$page -= 1;//so now, page === 0
...
$start = $page * $per_page;//which, since math, will be 0
...
$query_pag_datas = $this->control_model->data_for_pagination($start, $per_page,$city);
// you just called data_for_pagination(0, 15, 'London')
Since we can't see the data_for_pagination method, I'm going to assume that this first parameter is the number of results you are requesting. This makes sense because as the page number increases, the number of results will increase:
Page 2:
$page = $_POST['page'];//let's say we're posting page 2, so $page === 2
...
$page -= 1;//so now, page === 1
...
$start = $page * $per_page;//which, since math, will be 15
...
$query_pag_datas = $this->control_model->data_for_pagination($start, $per_page,$city);
// you just called data_for_pagination(15, 15, 'London')
Page 3:
$page = $_POST['page'];//let's say we're posting page 3, so $page === 3
...
$page -= 1;//so now, page === 2
...
$start = $page * $per_page;//which, since math, will be 30
...
$query_pag_datas = $this->control_model->data_for_pagination($start, $per_page,$city);
// you just called data_for_pagination(30, 15, 'London')
Hope that helps.
change
$page -= 1;
to
$page = ($page > 0 ) ? $page -1 : 0 ;
in the first click page is 0
so
0-1 => -1
-1 * 15 => -15 ;
your first offset is -15 !

Categories