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.
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 :
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).
Then we need to pass page number variable to jQuery code! It’s simple as that!
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.
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.
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!
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.