Load Dynamic Data on Page Scroll using jquery AJAX in PHP MYSQL


Load Dynamic Data on Page Scroll using jquery AJAX in PHP MYSQL,Data Load While Page Scroll,Load Data Automatically on Page Scroll,jQuery load more data on scroll

 

The Page scroll is a type of page load more data that doesn’t require the user to click a link to load dynamic data. Dynamic data is automatically loaded from the server as you scroll down the page like Facebook, YouTube and Amazon. infinite scrolling is a convenient way to load additional content onto web pages. This effect is the best replacement for Load more or Pagination links to auto load dynamic content from the server.

Loading data while scrolling Use Ajax to load external database content with jquery. When the user reaches the bottom of the web page, the data is fetched from the MySQL database and new content is loaded onto the web page as they scroll down the page. In this tutorial, we will show you how to load data as you scroll the page using jquery, Ajax, PHP, and MySQL.

See Also

  1. Load More Data from Database using jquery AJAX PHP with Mysqli
  2. Ajax Pagination using jquery with PHP and Mysqli

Output

Create Database Table

Tables must be created in the database to store publishing information. The following SQL creates a publishing table with some basic fields in a MySQL database.

--
-- Database: `blog_database`
-- --------------------------------------------------------
-- Table structure for table `posts`
--

CREATE TABLE `posts` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `post_heading` varchar(250) NOT NULL,
  `post_title` varchar(250) NOT NULL,
  `post_date` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Database Configuration

The dbConnection.php file is used to connect and select the MySQL database. Specify the database hostname ($servername), username ($dbUsername), password ($dbPassword), and name ($databasename) as per your MySQL credentials.

dbConnection.php

<?php

	// Database configuration 

	$sernamename  = "localhost";
	$dbUsername   = "root";
	$dbPassword   = "";
	$databasename = "blog_database";

	// Create database connection
	$con = new mysqli($sernamename, $dbUsername, $dbPassword, $databasename);
 
	// Check connection
	if ($con->connect_error) {
		die("Connection failed". $con->connect_error);
	}

?>

 

Create Load Dynamic Data on Page Scroll HTML Code

index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Load Dynamic Data on Page Scroll using jquery AJAX in PHP MYSQL</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="jumbotron text-center">
  <h2><b>Load Dynamic Data on Page Scroll using jquery AJAX in PHP MYSQL</b></h2>
</div>

<div class="container">
  <div id="postData">
    
  </div>
  <div class='loader-image' style='display:none;text-align:center;'>
    <img src='loader.gif' style="width:150px; height:150px; margin-top:-20px" />
  </div>
  <div id="loadBtn" style="text-align:center">
    
  </div>
</div>

</body>
</html>

jQuery & AJAX Code

The jQuery scroll () method is used to detect page scrolling, and an Ajax request is initiated when the user scrolls to the bottom of the page. Upon request from Ajax, the start published publication (start) is sent to the fetch_data.php file. After the successful Ajax method returns post data, HTML content is added to the post list.

<script type="text/javascript">
  $(document).ready(function(){

    var start = 0;
    var limit = 5;
    var reachedMax = false;

    getPostData();

    $(window).scroll(function(){
      if ($(window).scrollTop() == $(document).height()- $(window).height()) {
        getPostData();
      }
    });

    function getPostData(){
      $.ajax({
        url : 'fetch_posts.php',
        method: 'POST',
        dataType: 'text',
        cache:false,
        data : {getData:1,start:start,limit:limit},
        success:function(response){
          if(response=="") {
            $(".loader-image").hide();
            $("#loadBtn").html("<button type='button' class='btn btn-success btn-outline'>That is All</button>");
          }else{
            start += limit;
            $(".loader-image").show();
            $("#postData").append(response);  
          }
        }
      });
    }
  });
</script>

Load Dynamic Data on Page Scroll in HTML & PHP Code

Add a database configuration file (dbConnection.php) for connecting and selecting databases. Now take a limited number of entries from the Post table and list them on the web page.

<?php
	
	// Include Database connection file
	
	require_once 'dbConnection.php';

	if (isset($_POST['getData']) && !empty($_POST['getData'])) {
	
	    $start = $con->real_escape_string($_POST['start']);
	    $limit = $con->real_escape_string($_POST['limit']);

	    $query = "SELECT * FROM posts LIMIT $start, $limit";

	    $result = $con->query($query);

	if ($result->num_rows > 0) {

	    $output = "";

	    while ($row = $result->fetch_array()) {

	    $output.="<div class='panel panel-default panel-primary'>
	    	        <div class='panel-heading'>
	    	   	  <h4><strong> ".$row['post_heading']." </strong>
			    <small style='float:right;color:#fff'>".date("d-M-Y", strtotime($row['post_date']))."</small>
			  </h4>
			</div>
		       <div class='panel-body'><p style='font-size:17px;'> ".$row['post_title']." </p></div>
		     </div>";
	     }
	     echo $output;
	    }
	}

?>

You can always support by sharing on social media or recommending my blog to your friends and colleagues.    If you have any suggestions / problems about this tutorial, please comment on the  form below.😊


Leave a Reply

This Post Has 2 Comments

  1. Arvid

    It shows certain things repeatdly