I have an AJAX
pagination that is working, actually it does not work better, I'm trying to understand how AJAX
works with the url for pagination to work correctly.
What happens is that in normal pagination, without AJAX each of the links worked normal, more specifically the prev and the next: prev 1 2 3 4 next
, since the GET
was in the same url.
But with AJAX
only the sequence of numbers works. If I put $next = $current_page + 1;
the $current_page
variable always receives the current url without the value of $_GET["page_no"]
then with AJAX
if I'm on page 8 and click next on pagination, apparently not recognizing the GET in the current url, the next goes to page 1 instead of page 9.
I do not know if this has to do with working with date-haref
, rather than href
.
Thanks
class.crud.php
public function paginglink($query,$records_per_page)
{
$self = $_SERVER['PHP_SELF'];
$stmt = $this->db->prepare($query);
$stmt->execute();
$total_no_of_records = $stmt->rowCount();
if($total_no_of_records > 0)
{
?><ul class="pagination"><?php
$total_no_of_pages=ceil($total_no_of_records/$records_per_page);
$current_page=1;
if(isset($_GET["page_no"]))
{
$current_page=$_GET["page_no"];
}
if($current_page!=1)
{
$previous =$current_page-1;
echo "<li class='page-item'><a href='#' class='page-link' data-href='".$self."?page_no=1'>First</a></li>";
echo "<li class='page-item'><a href='#' class='page-link' data-href='".$self."?page_no=".$previous."'>Back</a></li>";
}
for($i=1;$i<=$total_no_of_pages;$i++)
{
if($i==$current_page)
{
echo "<li class='page-item'><a href='#' class='page-link' data-href='".$self."?page_no=".$i."' style='color:red;'>".$i."</a></li>";
}
else
{
echo "<li class='page-item'><ahref='#' class='page-link' data-href='".$self."?page_no=".$i."'>".$i."</a></li>";
}
}
if($current_page!=$total_no_of_pages)
{
$next=$current_page+1;
echo "<li class='page-item'><a href='#' class='page-link' data-href='".$self."?page_no=".$next."'>Next</a></li>";
echo "<li class='page-item'><a href='#' class='page-link' data-href='".$self."?page_no=".$total_no_of_pages."'>Last</a></li>";
}
?></ul><?php
}
}
AJAX
$('.page-link').click(function (e) {
e.preventDefault();
var url = $(this).data('href');
$.ajax({
url: url,
success: function (response) {
var html = $('<h1/>', {html : response}).find('#paginacao-ajax');
$('#paginacao-ajax').html( html )
}
});
})
Before you do the AJAX call you need to add the current page number onto the URL as a query variable, so that it becomes something like:
http://my-server.domain/path?page_no=4
That last bit is what is picked up by the $_GET in PHP. So in javascript you'll need some way to detect the current page number and add it onto the clicked URL.
P.S. I recommend using a library like URIJS to manipulate URLS, rather than just pasting it onto the end.
Try to use Method GET
$.ajax({
url: url,
method: "GET",
success: function (response) {
var html = $('<h1/>', {html : response}).find('#paginacao-ajax');
$('#paginacao-ajax').html( html )
}
});