Pagination is a crucial part of any website, especially if you have hundreds of database records that you want to group and display them as pages, and in modern days with the help of Ajax you can create pagination that doesn’t require any page reloading, users can stay in same page and navigate through vast numbers of records on fly. In this particular article we will be creating Ajax pagination using jQuery and PHP that can navigate though your database records without reloading the page.
This article has been updated, you can find other approach here.
We start off by creating a HTML file, which will make the Ajax requests to PHP file and load the response back to the page in a DIV element. We also have a loading image within the page to indicate loading processes.
We will load the first batch of records using load() method, and once the records are loaded, we can trigger click events in generated pagination links, which will again make the Ajax requests to the PHP file using page numbers and then the expected records will be loaded back in the results element.
Now we have jQuery code ready to make Ajax requests, we can create a new PHP file that will respond to Ajax requests made by the code above. This PHP file will work in background and have no direct contact with user.
After connecting to MySql database, we need to know total records of the table and break them into pages. Once we know this, we can fetch and display records determined by the MySql LIMIT clause. As you can see in the end of the script above, we have called the paginate_function() PHP function, this function expects certain parameters, we need to pass those parameters in order to generate pagination link.
Below is the PHP function that generates a nice pagination links for us, we just need to call it in our PHP script to create a pagination links depending on the parameters we pass to this function.
I have also created CSS which will make your pagination look great, you can find everything in sample file. You can download these files from links below. Just checkout the demo and test it on your website, I hope it will help you create nice pagination for your website, you can always comment below and help make this code better. If you want to load records like Facebook or Twitter style, you can checkout my other article — Loading More Results.