Menu Close

Infinite Scrolling on PHP website using jQuery and Ajax with example

0
(0)

Article which helps to load more data in a single page using Ajax and jQuery without affecting the page loading speed.

When you are fetching more data from the database to show on a single page, it may affect the page loading response. Let’s see the implementation of infinite scrolling functionality without affecting loading response using jQuery and Ajax.

Sometimes we need to load all news or blogs on a single page, it takes more time to get responses on simple PHP codes. But we can prevent the loading issue by using jQuery and Ajax, also it is a different method from that. Because we will load only limited data from the database once at a time and load another set of limited data from the database when users scrolling down. So that we can avoid loading issues. Data fetching will happen when the user scrolls down the page. Actually, this process is also called lazy loading. But it is very easy to build and very efficient to handle single pagination.

Let’s see how to display 100+ blogs on a single page without affecting the page loading time.

Step 1: Create a Database table

First, we need to create a ‘blog’ table in the database and declare id as primary key using the following SQL query. 

CREATE TABLE `blog` (
  `id` int(11) NOT NULL,
  `title` varchar(100) NOT NULL,
  `description` longtext NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `blog`
  ADD PRIMARY KEY (`id`); 

Step 2: Create a database connection

Create a connection to the MySQL database using PHP. Here, see the configuration file is database.php. So you can add this file to your main directory.

<?php
//connect to mysql database
$connection = mysqli_connect("localhost","username","password","databasename") or 
die("Error " . mysqli_error($connection));
?> 

Step 3: Fetch the blog data from MySQL table

Define the database connection initially and then fetch the data from the blog table using the following select query with limit and include the blog-date.php file to display the blog contents. Also, we have displayed the remaining blog contents when the user scrolls the page using Ajax and jQuery.

<?php
//add database configuration file
require('database.php');

//fetch data from database
$sql = "SELECT * FROM blog ORDER BY id DESC LIMIT 8";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));

//include blog data file
include('blog-data.php');

//close the database connection
mysqli_close($connection); 
?> 

Step 4: Display the blog data

Creating a blog-data.php file for displaying the blog contents.

<?php while($row = mysqli_fetch_array($result)) { ?>
<div class="postid" id="<?php echo $row['id']; ?>">
    <h2><a href=""><?php echo $row['title']; ?></a></h2>
    <p><?php echo $row['description']; ?></p>
    <hr style="margin-top:5px;">
</div>
<?php } ?> 

Step 5: Create Ajax configuration

To get remaining blog data when scrolling the page we need to use the following codes.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> 
<script>
$(window).scroll(function() {
    if($(window).scrollTop() + $(window).height() >= $(document).height()) {
        var last_id = $(".postid:last").attr("id");
        loadMore(last_id);
    }
});

function loadMore(last_id){
  $.ajax({
      url: 'load-more.php?last_id=' + last_id,
      type: "get",
      beforeSend: function(){
          $('.ajax-load').show();
      }
  }).done(function(data){
      $('.ajax-load').hide();
      $("#post-data").append(data);
  }).fail(function(jqXHR, ajaxOptions, thrownError){
      alert('server not responding...');
  });
}
</script> 

Step 6: Create a PHP file for Ajax Call

Creating a  load-more.php file for displaying remaining blog contents. Use the below codes,

<?php
//add database configuration file
require('database.php');

//fetch data from database
$sql = "SELECT * FROM blog WHERE id < '".$_GET['last_id']."' ORDER BY id DESC LIMIT 8";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
include('blog-data.php'); ?> 

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Share

Posted in Ajax, JavaScript, jQuery, MySQL, PHP

Leave a Reply

Your email address will not be published. Required fields are marked *

You can also read...