How to Create Ajax Scroll Down Pagination with Php and Mysql





This time I am posting ajax scroll down pagination with PHP and MySQL. In this tutorial it has two demos; first one where records are displayed when you scroll down to the bottom of the page and the other one is where you scroll down the page and you get a button asking to display next set of data.

Create database and table in MySQL database

First of all lets start with making mysql database and table. I will be using country names.

The database part is done, now the html part. Add a div container with an unique id that will hold all the data. Also make two more container for loader image and loader message.

Implementing ajax scroll down pagination with PHP and MySQL

In this demo, user will scroll down to the bottom of page and data will be displayed accordingly until all data is displayed.

First let us create a database connection file config.php. I will be using PDO classes. In case you want to learn by using some example, I have made a small mini project with PDO classes. Download Simple address book with php and mysql using pdo.

Moving on now we need to call an ajax request on page load to get the first set of data, after that when user scrolls down the page the next set of data will be displayed automatically. I have created a function displayRecords() that will display the data via ajax request. Check the code below.

You have to call this function on page load. I have added 3 javascript variables limit, offset, busy.

  • limit – The number of records to display per request.
  • offset – The starting pointer of the data.
  • busy – Check if current request is going on or not.




Trick behind the scroll down pagination

The main trick for this scroll down pagination is binding the window scroll event and checking with the data container height.

Now on the php part. check the code below its very simple I have used offset with limit.

That was all for demo1, now in demo 2 the trick is very simple, when first set of records is displayed, I am adding a buton with the results set to the div container which is binded with the click event. So when user clicks on it, an ajax request will be fired. When there is no data, I am adding a attribute with the button data-attr=”nodata” which provides a check when user tries to fetch the records even if its not there.




Download Project Files