jQuery AJAX Pagination PHP: 7-Step Complete Guide

jQuery AJAX Pagination PHP: 7-Step Complete Guide - Image

In this article, we’re going to explain how to paginate your data using PHP and AJAXwithout page reloads and without a click, Yes without anywhere click on the page.

This example will show you pagination onScroll. So, let's get started with Jquery Ajax pagination with PHP.

This is an amazing exercise on the JQuery ajax and PHP. We are using the jQuery library for Ajax request and MySQL for a database with PHP.

How jQuery AJAX pagination PHP works

Offset and limit control the result window

Pagination divides a large result set into smaller windows. The limit value controls how many rows arrive in one request, while offset tells the database where the next window begins. With a limit of 15, the first request starts at offset 0 and the next request starts at offset 15.

Infinite scroll is only one presentation option. The same endpoint can support numbered buttons, a “Load more” control, or a manually triggered refresh. Choose the interface based on how easily visitors need to revisit earlier results.

Keep the response predictable

The browser should know whether a request succeeded, whether more rows exist, and which markup or data belongs to the current request. Returning a small JSON object is usually easier to maintain than mixing table headers, rows, and error text in one unstructured response.

  • Return the rows or a rendered fragment.
  • Return a count or has_more flag when the client needs to stop loading.
  • Return a clear error status when the request is invalid.

Dofollow and nofollow links in seo

Cal these JQuery link on your page to use JQuery ajax request and bootstrap for responsive page.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

In this example I am fetching records from the database and then displaying on the page. You can change the limit of records per page according to you. Now we are going to set these limit and offset and call once on the page and onScroll:

Prepare reliable infinite scroll

Prevent duplicate requests

The busy flag prevents the scroll handler from starting a second request while the first one is still running. Always reset it in both the success and failure paths, or a temporary server error can leave the page permanently stuck.

It is also useful to set a loading threshold before the document bottom. Waiting until the exact final pixel can make the interface feel empty, especially on a fast scroll or a slow connection.

Stop when the data ends

If the endpoint returns fewer rows than the requested limit, there may be no additional records. Track that state and stop binding more requests. Otherwise the browser can keep asking for empty pages every time the visitor reaches the bottom.

let hasMore = true;
function loadNextPage() {
  if (busy || !hasMore) return;
  busy = true;
  $.post('ajax_page.php', {action: 'show_list', offset, limit})
    .done(function (response) {
      $('#result').append(response.html);
      offset += response.count;
      hasMore = response.has_more;
    })
    .fail(function () {
      $('#message').text('Could not load more records.');
    })
    .always(function () {
      busy = false;
    });
}
var busy = false;
var offset = 0;
var limit = 15;
$(window).scroll(function(){
	if(($(window).height() + $(window).scrollTop())+400 >= $(document).height() && !busy){
		busy = true;
		offset = offset + limit;
		getresult(offset, limit)
	}
});

Your index page should be like this with a ajax request:

Improve the pagination interface

Use accessible loading feedback

A spinning icon alone does not explain what is happening to every visitor. Give the loading region a label or status message, make it visible while a request is active, and provide a retry option after a failure.

Rows appended to a table should preserve valid table structure. Keep the header in a thead and add records inside a tbody. If the server returns HTML, escape user-controlled values before inserting them into the response.

Support more than scrolling

Infinite scroll can make the footer difficult to reach and can be inconvenient for keyboard users. A “Load more” button is a useful fallback because it gives the visitor control and provides a clear focus target.

  • Show a visible status while data is loading.
  • Keep the control usable with a keyboard.
  • Explain when no more records are available.
  • Offer a retry action when the request fails.
<!DOCTYPE html>
<html lang="en">
<head>
  <title>JQuery Ajax Pagination with Bootstrap and php</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
  <h2 class="text-danger">JQuery Ajax Pagination with Bootstrap and php</h2>
  <table id="result" class="table table-striped"></table>
  <div id="loader-icon"><i class="fa fa-refresh fa-spin" style="font-size:20px"></i></div>
</div>
</body>
</html>
<script>
function getresult(offset,limit) { 
	$.ajax({
		url: 'ajax_page.php',
		type: "POST",
		data: {action:'show_list',offset:offset,limit:limit},
		beforeSend: function(){
			$('#loader-icon').show();
		},
		complete: function(){
			$('#loader-icon').hide();
		},
		success: function(data){
			$("#result").append(data);
			window.busy = false;
		},
		error: function (jqXHR, textStatus, errorThrown) {
		  if (jqXHR.status == 500) {
			  console.debug("Internal error: " + jqXHR.responseText)
		  } else {
			  console.debug("Unexpected error.")
		  }
		}        
	});
}
var busy = false;
var offset = 0;
var limit = 15;
$(window).scroll(function(){
	if(($(window).height() + $(window).scrollTop())+400 >= $(document).height() && !busy){
		busy = true;
		offset = offset + limit;
		getresult(offset, limit)
	}
});
getresult(offset, limit);
</script>

Now we are going to setup database configuration file:

Secure the PHP pagination endpoint

Validate offset and limit on the server

Never accept arbitrary pagination values without checking them. Convert them to integers, reject negative offsets, and cap the maximum limit. This protects the endpoint from unexpected queries and keeps response sizes manageable.

$offset = filter_input(INPUT_POST, 'offset', FILTER_VALIDATE_INT);
$limit = filter_input(INPUT_POST, 'limit', FILTER_VALIDATE_INT);
if ($offset === false || $offset < 0 || $limit === false || $limit < 1 || $limit > 100) {
    http_response_code(422);
    exit('Invalid pagination values');
}

Use a stable sort order

Pagination needs an explicit and repeatable ORDER BY. Without a stable order, rows can appear twice or disappear between requests when the table changes. Sort by a unique column, such as an ID, and add a second condition when ties are possible.

Do not insert raw offset or limit strings into SQL. After validation, use a prepared statement or a safely bounded integer value, and select only the columns the page actually displays.

<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "mydatabase";
// Create connection
$connection = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$connection) {
    die("Connection failed: " . $connection->connect_error);
}
function close_db(){
	mysqli_close($connection);
}
?>

Your ajax page is:

Test and troubleshoot AJAX pagination

Test the first and later pages

Check the initial request with offset 0, then check the next request after scrolling. Confirm that the first response includes the header only once and that later responses contain rows without repeating the header.

Use the browser Network panel to inspect request payloads, response status, response size, and timing. A 404 usually points to the endpoint path, a 422 suggests invalid pagination values, and a 500 requires checking the PHP logs and database query.

Plan for changing data

If records are inserted or removed while a visitor scrolls, offset pagination can shift the boundary between pages. For rapidly changing feeds, consider cursor pagination based on the last returned ID or timestamp. For a stable administrative table, validated offset pagination may be sufficient.

  • Check empty results and the final page.
  • Test a slow connection and a failed request.
  • Confirm that HTML output is escaped.
  • Verify that database errors are logged privately.

FAQ

What is jQuery AJAX pagination PHP?

It is a pattern where jQuery requests one page of PHP-generated data in the background and adds the result to the current page without a full reload.

How do offset and limit work?

Limit sets the number of rows returned. Offset sets the position at which the database begins reading the next page.

How do I stop infinite scroll at the end?

Return the number of rows or a has_more value from PHP and stop new requests when the endpoint reports that no records remain.

Is AJAX pagination secure?

The endpoint must validate pagination values, authorize access, use safe SQL, and escape output. AJAX itself is not a security boundary.

Conclusion

A dependable jQuery AJAX pagination PHP implementation combines a small client request with a carefully validated server endpoint. Use a busy flag, stable sorting, loading feedback, and an explicit end-of-results state.

Start with the supplied example, test each request in the Network panel, and then choose infinite scroll, a Load more button, or numbered pagination according to the needs of your visitors.

<?php 
require_once('config.php');
if(isset($_POST['action'])){
	$action = $_POST['action'];
	
	if($action == 'show_list'){
		$offset = $_POST['offset'];
		$limit = $_POST['limit'];
		
		$mysql_query = mysqli_query($connection, "Select * from country Limit $offset, $limit");
		if($offset == 0){
			echo "<thead>
					<tr class='text-info'>";
				while($mysql_query_fields = mysqli_fetch_field($mysql_query)){
					$mysql_fields[] = $mysql_query_fields->name;
					echo "<th align='left'>".ucfirst($mysql_query_fields->name)."</th>";
				}
			echo "</tr>
				</thead>";
		}
		else{
			while($mysql_query_fields = mysqli_fetch_field($mysql_query)){
				$mysql_fields[] = $mysql_query_fields->name;
			}
		}
		while($mysql_rows = mysqli_fetch_array($mysql_query)){
		echo "<tr>";
			foreach($mysql_fields as $fields){
				echo "<td>".$mysql_rows[$fields]."</td>";
			}
		echo "</tr>";
		}
	}
	else{
		 echo "Invalid Method!";
	}
}
else{
	echo "Invalid Calling Method!";
}
close_db();
?> 

Related posts

(1) Comments

  • User Pic

    Excellent post. Nice work keep it up. Thanks for sharing the knowledge.

Write a comment