Load data dynamically on page scrolling using jQuery, Ajax, PHP, and MySQL

  •  
  •  
  •  
  •  
  •  
  •  

When we have too many records or contents to display on the web page, we used pagination. Pagination simply divides all the records among pages, such as page 1, page 2 and so on. But, nowadays we replaced this pagination mechanism with a more friendly feature that loads data dynamically from the database on page scrolling. So, in this tutorial, I will show you how to load data dynamically on page scrolling using jQuery, Ajax, PHP, and MySQL. This tutorial explained in very easy steps with live demo and complete source code to download. You may also like to read — Bootstrap pagination using PHP and MySQL.

Load data dynamically on page scrolling using jQuery, Ajax, PHP, and MySQL

File Structure

Before starting this tutorial please look at the file structure.

  • db.php (database configuration file)
  • index.php (main UI file)
  • get-data.php (fetch data from database)
  • bootstrap folder (CSS and js)

Database Configuration (db.php)

<?php
define('HOSTNAME','localhost');
define('DB_USERNAME','USERNAME');
define('DB_PASSWORD','PASSWORD');
define('DB_NAME', 'DATABASE_NAME');

//global $con;
$con = mysqli_connect(HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_NAME) or die ("error");
// Check connection
if(mysqli_connect_errno($con))	echo "Failed to connect MySQL: " .mysqli_connect_error();
?>

Change the database name, database username and password according to your credentials. To get the dummy sample data please download the complete source code from the below download link.

Include Bootstrap Files (index.php)

<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<script src="bootstrap/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>

This example is responsive in design by using bootstrap.

HTML – Display Data (index.php)

<body>	
  <div class="container-fluid mtb-margin-top">
    <div class="row">
      <div class="col-md-12">
        <div id="output"><?php include('get-data.php');?></div>
        <div class="loader"><img src="loader.gif" /></div>
      </div>
    </div>
  </div>
</body>

The above HTML code is very simple to understand. On page load it will display the content from the get-data.php page.

jQuery and Ajax – Load Data Dynamically (index.php)

<script type="text/javascript">
  $(window).scroll(function() {
   if($(window).scrollTop() == ($(document).height() - $(window).height())) {
     var total_pages = parseInt($("#total_pages").val());
     var page = parseInt($("#page").val())+1;
     if(page <= total_pages) {
       load_more_data(page, total_pages);
     } 
   }
  });
  
  function load_more_data(page, total_pages) {	 	
   $("#total_pages, #page").remove();	 	
   $.ajax({
     url: 'get-data.php',
     type: "POST",
     data: {page:page},
     beforeSend: function(){
       $(".loader").show();
     },
     complete: function(){
       $('.loader').hide();
       if(page == total_pages) {
         $(".loader").html('... No more article! ...').show();
       }
     },
     success: function(data){
       $("#output").append(data);
     },
     error: function(){
       $(".loader").html("No data found!");
     }
   });
  }
</script>

When user scrolls down the page the $(window).scroll(function() {..}) funtion checks the position of the scrollbar and call the load_more_data() if it reaches at the bottom of the page. load_more_data() function sends data using post method to the get-data.php page and appends the data at the bottom of the output div whatever it receives from the get-data.php page using jQuery and Ajax.

PHP And MySQL – Fetch Data From Database (get-data.php)

<?php include('db.php'); ?>
<?php
/*How many records you want to show in a single page.*/
$limit = 10;
if(isset($_POST['page']) && $_POST['page'] != "") {
  $page = $_POST['page'];
  $offset = $limit * ($page-1);
} else {
  $page = 1;
  $offset = 0;
}


$query = "select count(*) 'total_rows' from `posts`";
$res = mysqli_fetch_object(mysqli_query($con, $query));
$total_pages = ceil($res->total_rows/$limit);


$query  = "select * from `posts` limit $offset, $limit";
$res = mysqli_query($con, $query);
if(mysqli_num_rows($res) > 0) {
  $results = "";
  $results .= '<input type="hidden" name="total_pages" id="total_pages" value="' . $total_pages . '">';
  $results .= '<input type="hidden" name="page" id="page" value="' . $page . '">';
  $results .= '<div id="results">';
  while($row = mysqli_fetch_object($res)) {
    $results .= '<h1 class="post-title"><a href="'.$row->link.'" target="_blank">'.$row->title.'</a></h1>';
    $results .= '<p class="text-justify">' . $row->content . '</p>';
  }
  $results .= '</div>';
  echo $results;
}
?>

<?php mysqli_close($con); ?>

At last, get-data.php fetches records dynamically from the database based on the data receives from the jQuery Ajax request.

Try online live demo on – load data dynamically using jQuery, Ajax, PHP and MySQL from the below demo link and download the complete source code from the below download link. Please like and share this tutorial with others.

About Mitrajit

4 comments on “Load data dynamically on page scrolling using jQuery, Ajax, PHP, and MySQL

Leave a Reply

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

Prove you are a human *