jQuery AJAX Pagination

by Vincy. Last modified on September 23rd, 2022.

In this tutorial, we are going to see the simple code for pagination using jQuery AJAX and PHP. This code will have first, last, previous, next and other pagination links. On clicking each link it invokes the AJAX handler to request limited page results from the database.

Go through the best secure and simple pagination script in PHP using the MySql database.

The steps for implementing jQuery AJAX pagination are,

  1. Sending page requests via AJAX.
  2. Calculate query limit to retrieve data.
  3. Create pagination links and apply styles.
  4. Show results and pagination links.

View Demo

Sending Page Request via AJAX

In this code, we are sending an initial request for a page getresult.php.

jquery ajax pagination output

This page will do all server-side functions and respond to the pagination request. AJAX handlers insert this response data into the target selectors.

index.php

<html>
<head>
<title>jQuery AJAX Pagination</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-2.1.1.js"></script>
<script>
function getresult(url) {
    $('#loader-icon').show();
    $.ajax({
        url: url,
        type: "GET",
        data: { rowcount: $("#rowcount").val() },
        success: function(data) {
            $("#pagination").html(data);
            $("#loader-icon").hide();
        },
        error: function() { }
    });
}
</script>
<style>
#loader-icon {
    text-align: center;
    position: relative;
    top: 10px;
}
</style>
</head>
<body>
    <div id="pagination">
        <input type="hidden" name="rowcount" id="rowcount" />
    </div>
    <script>
getresult("getresult.php");
</script>
</body>
</html>

Calculate Query Limit

Since loading the bulk of data takes much time, the pagination is for the quick retrieve/load. So, we have to calculate the start and end limit based on the page request. The code is,

getresult.php

<?php
require_once ("db.php");
require_once ("pagination.class.php");
$perPage = new PerPage();
$sql = "SELECT * from php_interview_questions";
$paginationlink = "getresult.php?page=";
$page = 1;
if (! empty($_GET["page"])) {
    $page = $_GET["page"];
}
$start = ($page - 1) * $perPage->perpage;
if ($start < 0) {
    $start = 0;
}
$statement = $connection->prepare($sql);
$statement->execute();
$result = $statement->get_result();
?>

Create Pagination Links and Apply Styles

For creating a total number of page links, we need to pass the database result count if found already.

getresult.php

<?php
$perpageresult = $perPage->perpage($result->num_rows, $paginationlink);
?>

The function per page will create all pagination links and apply styles based on the status of the page whether it is active or not applicable. The code is,

pagination.class.php

<?php

class PerPage
{

    public $perpage;

    function __construct()
    {
        $this->perpage = 1;
    }

    function perpage($count, $href)
    {
        $output = '';
        if (! isset($_GET["page"]))
            $_GET["page"] = 1;
        if ($this->perpage != 0)
            $pages = ceil($count / $this->perpage);
        if ($pages > 1) {
            if ($_GET["page"] == 1)
                $output = $output . '<span class="disabled"><<</span><span class="disabled"><</span>';
            else
                $output = $output . '<a class="link" onclick="getresult(\'' . $href . (1) . '\')" ><<</a><a class="link" onclick="getresult(\'' . $href . ($_GET["page"] - 1) . '\')" ><</a>';

            if (($_GET["page"] - 3) > 0) {
                if ($_GET["page"] == 1)
                    $output = $output . '<span id=1 class="current">1</span>';
                else
                    $output = $output . '<a class="link" onclick="getresult(\'' . $href . '1\')" >1</a>';
            }
            if (($_GET["page"] - 3) > 1) {
                $output = $output . '...';
            }

            for ($i = ($_GET["page"] - 2); $i <= ($_GET["page"] + 2); $i ++) {
                if ($i < 1)
                    continue;
                if ($i > $pages)
                    break;
                if ($_GET["page"] == $i)
                    $output = $output . '<span id=' . $i . ' class="current">' . $i . '</span>';
                else
                    $output = $output . '<a class="link" onclick="getresult(\'' . $href . $i . '\')" >' . $i . '</a>';
            }

            if (($pages - ($_GET["page"] + 2)) > 1) {
                $output = $output . '...';
            }
            if (($pages - ($_GET["page"] + 2)) > 0) {
                if ($_GET["page"] == $pages)
                    $output = $output . '<span id=' . ($pages) . ' class="current">' . ($pages) . '</span>';
                else
                    $output = $output . '<a class="link" onclick="getresult(\'' . $href . ($pages) . '\')" >' . ($pages) . '</a>';
            }

            if ($_GET["page"] < $pages)
                $output = $output . '<a  class="link" onclick="getresult(\'' . $href . ($_GET["page"] + 1) . '\')" >></a><a  class="link" onclick="getresult(\'' . $href . ($pages) . '\')" >>></a>';

            else
                $output = $output . '<span class="disabled">></span><span class="disabled">>></span>';
            $output = $output . '<span id="loader-icon">
                <img src="LoaderIcon.gif" />
                </span>';
        }
        return $output;
    }
}
?>

Show Results and Pagination Links

Finally, the requested PHP script will form the output HTML for printing database results and pagination link.

getresult.php

<?php
$query = $sql . " limit " . $start . "," . $perPage->perpage;
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->get_result();
$output = '';
while ($row = mysqli_fetch_array($result)) {
    $output .= '<div class="question"><input type="hidden" id="rowcount" name="rowcount" value="' . $result->num_rows . '" />' . $row["question"] . '</div>';
    $output .= '<div class="answer">' . $row["answer"] . '</div>';
}
if (! empty($perpageresult)) {
    $output .= '<div id="pagelink">' . $perpageresult . '</div>';
}
print $output;
?>

Data printed above will be read as an AJAX response and inserted into the target selector.

Refer AJAX pagination with PHP if you are looking for a PHP solution with jQuery.

success: function(data){
	$("#pagination").html(data);
}
<div id="pagination">
// AJAX Response will be Inserted
</div>

View DemoDownload

Comments to “jQuery AJAX Pagination”

Leave a Reply to Mizan Cancel reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page