This post will help you to understand how to create simple Ajax pagination with jQuery and PHP.
Web page takes a lot of time to load data when there is a huge record in the database. To solve this issue, we use pagination or AJAX pagination.
AJAX pagination help to load record smoothly.
Webpage takes a lot of time to load data when there is huge record in database. To solve this issue, we use pagination to load record smoothly.
In this tutorial, we will see AJAX Pagination with jQuery and PHP. User can see record without reloading the page.
You can also like
Simple Pagination with PHP and MySQL.
Steps
- Create a database connection file
- Write Markup to Load and display results
- Show Pagination Format
- Show Pagination Results via AJAX
- Process AJAX Pagination Results in PHP
Let’s see how to create ajax pagination.
Table of Contents
Database Connection
<?php
$dbname = "test";
$dbuser = "root";
$dbpw = "";
$dbhost = "localhost";
$conn = mysqli_connect($dbhost, $dbuser, $dbpw, $dbname); // Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Write Markup to Load and Display Results
<div id="content"></div>
Show Pagination Format
<?php
include_once 'config.php';
$sql = mysqli_query($conn, "SELECT course_id FROM courses");
$total_records = mysqli_num_rows($sql);
$limit = 10;
$total_pages = ceil($total_records / $limit);
//start pagination
$PaginationLinks = "<ul class='pagination'>";
for ($i=1; $i<=$total_pages; $i++) {
$PaginationLinks .= "<li><a href='".$_SERVER['PHP_SELF']."?page=".$i."' class='link' onclick='getResults(".$i.")'>".$i."</a></li>";
}
$PaginationLinks .= "</ul>"; //end pagination
//show pagination
echo $PaginationLinks;
?>
Show Pagination Results via AJAX
First include jQuery library
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".link").click(function(e){
e.preventDefault();
});
});
function getResults(page) {
$.ajax({
type: "GET",
url: "result.php",
data: {page : page},
cache: false,
success: function(html) {
$("#content").html(html);
}
});
}
//default homepage content loading
getResults(1);
</script>
Process AJAX Pagination Results in PHP
<?php[sociallocker] Download [/sociallocker]
include_once 'config.php';
$limit = 10;
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$start_from = ($page-1) * $limit;
$sql = mysqli_query($conn, "SELECT * FROM courses LIMIT $start_from, $limit");
?>
<table class="table table-bordered table-striped">
<thead>
<tr><th>ID</th><th>Name</th></tr>
<thead>
<tbody>
<?php while($row = mysqli_fetch_array($sql)) {
?>
<tr>
<td><?php echo $row["course_id"]; ?></td>
<td><?php echo $row["course_name"]; ?></td>
</tr>
<?php } ?>
</tbody>
</table>