we are going to see an example PHP code to add ajax pagination to a list of records retrieved from database. pagination is a very important part where huge numbers of records are listed from the database.
jQuery function call to get data in mysql table using Ajax. INDEX.HTML
var xhr;
function request_call(url,mydata)
{
if(xhr && xhr.readyState != 4){
xhr.abort();
}
xhr = $.ajax({
url: url,
type :'post',
dataType: 'json',
data : mydata,
});
}
function pagignation()
{
request_call("pagignation.php?pagignation=true","page="+1);
xhr.success(function( mydata ) {
$('#render_string').html(mydata.success);
$('#pagi').html(mydata.pagi);
});
}
pagignation();
In avbove Request Call function (request_call) to call url in pagignation.php
define('DB_SERVER', "localhost");
define('DB_USER', "root");
define('DB_PASS', "");
define('DB_DATABASE', "student");
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
if(isset($_REQUEST['pagignation']))
{
$html = $pagi = '';
$limit = 2;
if (!empty($_POST['page']))
{
$page = $_POST['page'];
}
else
{
$page=1;
}
$start_from = ($page-1) * $limit;
$page = $_POST['page'];
$query = mysqli_query($con, "SELECT * FROM student_detail limit $start_from, $limit ");
$totalcount = mysqli_query($con, "SELECT * FROM student_detail");
$total_records = mysqli_num_rows($totalcount);
$total_pages = ceil($total_records / $limit);
if($total_records>0)
{
while ($row = mysqli_fetch_assoc($query))
{
$html.='<tr>'
. '<td>'.$row['first_name'].'</td>'
. '<td>'.$row['last_name'].'</td>'
. '<td>'.$row['email'].'</td>'
. '<td>'.$row['mobile'].'</td>'
. '</tr>';
}
if(!empty($total_pages))
{
$pagi.='<ul class="pagination" id="pagination">'
. '<li style="cursor: pointer;" id="1">First</li>';
for($i=1; $i<=$total_pages; $i++)
{
if($i == 1)
{
$pagi.=' <li class="activepagignation" style="cursor: pointer;" id="'.$i.'">'.$i.'</li>';
}
else
{
$pagi.=' <li class="" style="cursor: pointer;" id="'.$i.'">'.$i.'</li>';
}
}
$pagi.='<li class="" style="cursor: pointer;" id="'.$total_pages.'">Last</li></ul>';
}
}
else
{
$html.= '<tr><td>No Record Found!!</td></tr>';
$pagi.= '';
}
$data['pagi']= $pagi;
$data['success'] = $html;
echo json_encode($data);
}
Now Finally retrive data in Html page after pagination event call in jquery on click event.
$('#pagi').delegate('#pagination li', 'click', function() {
$("#pagination li").removeClass('activepagignation');
$(this).addClass('activepagignation');
var pageNum = this.id;
request_call("pagignation.php?pagignation=true","page="+pageNum);
xhr.success(function( mydata ) {
$('#render_string').html(mydata.success);
});
});
In above tutorial teach you How to create Ajax Pagination in PHP.