Simple Ajax Pagination With jQuery and PHP

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

  1. Create a database connection file
  2. Write Markup to Load and display results
  3. Show Pagination Format
  4. Show Pagination Results via AJAX
  5. Process AJAX Pagination Results in PHP

Let’s see how to create ajax pagination.

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

View Demo

[sociallocker] Download [/sociallocker]

Leave a Comment