Loading More Results From Database Using jQuery Ajax
You might have seen the implementation of Ajax based data loading technique at Facebook, Twitter or some other sites. Instead of showing pagination links, why not let users load data dynamically on a button click. In this article we’ll try to adopt the technique to make similar loading page for our projects using jQuery.
You may also want to checkout similar tutorial Auto Load More Data On Page Scroll. In my previous post Simple Ajax Pagination, I have explained how to create Ajax Pagination using jQuery. Here we will be doing precisely the same thing, in-fact we’ll be borrowing all sample files from previous post. Everything stays the same, only index.php file will be modified here.
As explained in previous post, this is the configuration file to store our MySql database username and password, and also to connect to MySQL using PHP mysqli_connect.
Here we wont be generating any pagination links like before, we only need to get total records and break them to page numbers, which we will be using with jQuery.
Now we have total page number, its time to write some jQuery codes. Like I said, we’ll only be modifying index.php page here.
Since we need to append results into the element, and jQuery .load() method won’t let us insert results as the last child, we will be using jQuery .post() instead of .load() method we previously used in Simple Ajax Pagination examples.
Everything’s set, here’s our HTML that contains Load more button, a loading image and place to append the data from fetch_pages.php. Loading image is hidden at first, when user clicks on load more button, we need to show the loading image to indicate data is loading.
In previous post, I talked about posting page number to fetch_pages.php from index page, to track the starting point of record. Here, we apply the same method. We pass page number to get starting point of record in fetch_pages.php file.
That’s it! we should have a nifty jQuery based data loading page by now. Don’t forget to checkout the demo and download the whole thing in your computer, downloadable file comes along with style file, image and latest jQuery file. Good luck!
Saran Chamling. (He loves the web technology, and enjoys designing, exploring and writing about it @saaraan.com).