Simple Ajax Pagination with jQuery & PHP

Pagination can get complicated depending on the size of records in the database, especially when you want to group number of links, display next/previous links etc. In this article we’ll only focus on creating simple ajax based pagination using bootpag jQuery plugin. I am pretty sure its the most simplest example you can find on the net.

Ajax Pagination

Configuration

Let’s start with configuration file to store our MySql database username and password, and also to connect to MySQL using PHP mysqli_connect. We are using PHP mysqli_connect() here, not regular mysql_connect(), you can learn more about mysqli here . Anyways, here’s our configuration file :

1
2
3
4
5
6
7
8
9
<?php
$db_username = 'root';
$db_password = '';
$db_name = 'demo';
$db_host = 'localhost';
$item_per_page = 5;

$connecDB = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');
?>

Get total page number

To generate links, we need to know the total number of pages, formula is simple, we just divide total number of records like this (total record / item per page = number of pages).

1
2
3
4
5
6
7
8
9
10
<?php
include("config.inc.php");

$results = mysqli_query($connecDB,"SELECT COUNT(*) FROM paginate");
$get_total_rows = mysqli_fetch_array($results); //total records

//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);  

?>

Then we need to pass page number variable to jQuery code! It’s simple as that!

Generate Pagination Using jQuery bootpag Plugin

Once we have the page number we need to create pagination links, fortunately we have Bootpag jQuery plugin, which allows us to create dynamic pagination using the value of total pages we calculated in above example. Next we use load() Ajax method to fetch the records. load() is an excellent AJAX method to load data from server. We’ll utilize this method to perform the pagination task without refreshing the page, we’ll also be adding some basic effects like loading animation. When user clicks on pagination link, the page number will be sent to fetch_pages.php and then the result will be loaded in specified DIV element.

1
2
3
4
5
6
7
8
9
10
11
12
13
<script type="text/javascript">
$(document).ready(function() {
    $("#results").load("fetch_pages.php");  //initial page number to load
    $(".pagination").bootpag({
       total: <?php echo $pages; ?>, // total number of pages
       page: 1, //initial page
       maxVisible: 5 //maximum visible links
    }).on("page", function(e, num){
        e.preventDefault();
        $("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
        $("#results").load("fetch_pages.php", {'page':num});
    });
});

Displaying Results and Pagination Links

We have PHP & jQuery codes ready to generate pagination links and fetch records from the database, all we need to do is place below codes within the body of the page.

<div class=”pagination”> displays the pagination links and <div id="results"></div> to dump the Ajax results.

1
2
<div id="results"></div>
<div class="pagination"></div>

Fetching Pages

Below is the PHP code for “fetch_pages.php”. When the page number is passed using jQuery .load() method, we need to get starting point of record, and number of records to display per page. The MySQL LIMIT clause can be used to limit the results we want from the database, we’ll just pass these two values as arguments, and have our records fetched, that’s it!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php
include("config.inc.php"); //include config file

//sanitize post value
if(isset($_POST["page"])){
    $page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
    if(!is_numeric($page_number)){die('Invalid page number!');} //incase of invalid page number
}else{
    $page_number = 1;
}

//get current starting point of records
$position = (($page_number-1) * $item_per_page);

//Limit our results within a specified range.
$results = mysqli_query($connecDB, "SELECT id, name, message FROM paginate ORDER BY id ASC LIMIT $position, $item_per_page");

//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
    echo '<li id="item_'.$row["id"].'">'.$row["id"].'. <span class="page_name">'.$row["name"].'</span><span class="page_message">'.$row["message"].'</span></li>';
}
echo '</ul>';

Conclusion

You can use above examples to create your own sophisticated ajax driven pagination, below you’ll find downloadable files and link to demo page. And also you might find my other similar post helpful — loading more results dynamically. Good Luck!

There’s another way to paginate your records using jQuery and PHP click here.

Download Demo

14 Comments Add Comment

  • It really works.Thanks

     Reply
  • How to show “…” in the pagination (in case we have 1000 rows of data-table

     Reply
  • Thanks a lot. It helps me. I have done this job with PDO connection. One more thing, it conflicts with bootstrap. So I also have changed .pagination class.
    It;s working nice :)

     Reply
  • nice example

     Reply
  • Hi,

    How to make use this code for fetching images from the mySQL database ?
    Would highly appreciate.

     Reply
  • Nirav_Mendhirata

    Hello,

    Can some one help me? I have used above code but there is some problem as it is showing active page numbers on the page where there is no data.Also three black dots (…) are displayed.

    PLease some reach me with solution asap on email : [email protected]

    Thanks

     Reply
  • Great tuto
    thanks you very much
    it’s so nice :)

     Reply
  • sir kindely tell me how to put table wise data from db and it should be show at least ten records

     Reply
  • Hello,
    I’m a beginner in coding. Is there a way of paging these li elements (like the ones in your demo) without using PHP at all, without knowing the total number of pages and without making use of CSS in jQuery?
    Any help is greatly appreciated. Thank you in advance.

     Reply
  • Results of first page display well but the navigator links are not working, i can select them but it shows no results. Any clue of what could it be? Thanks!

     Reply
    • My problem was here, in fetch_pages.php :

      1
      $page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);

      i guess my server does not have that functions.

    • Dani i Am also facing the same problem ,
      even when i click demo it does not show any pagination or data fetched
      Did you get the solution?

  • Angelica Morales

    Funciona perfecto, :) Gracias por compartirlo.

     Reply
  • hi sir,
    im newbie here
    do you have an example code of next/previous onclick
    using ajax/jquery php
    thanks in advance

     Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.