Thursday 30 March 2017

Load Content while Scrolling with Jquery Ajax PHP



In this post, we have make discussion on how to auto load data on web page dynamically when user scrolls the page by using Ajax JQuery with PHP Script. We have already make this type of tutorial on which we have load data on web page by clicking on button, but in this post we will load data on web page when user has been scroll down the page.

For loading Dynamic data on page while scrolling of web page, when user has been scroll the page then at that time Ajax Event has been fire and it will send request to PHP Script for getting data from Mysql table. It will fetch data from table and convert that data to HTML format and send back to Ajax request and it will display on web page. In this post we have use scroll() event of Jquery to fire Ajax request.

First we have define two div tag, in one tag we will display table content in HTML format and in second div tag we will display one button with text like please wait.


<div id="load_data"></div>
   <div id="load_data_message"></div>


In JQuery we have make on function that fetch data from table and display on web page in specified div tag. In this function we have use Ajax request that fetch data from table and convert them to html format and display on web page.


var limit = 7; //The number of records to display per request
 var start = 0; //The starting pointer of the data
 var action = 'inactive'; //Check if current action is going on or not. If not then inactive otherwise active
 function load_country_data(limit, start)
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   data:{limit:limit, start:start},
   cache:false,
   success:function(data)
   {
    $('#load_data').append(data);
    if(data == '')
    {
     $('#load_data_message').html("<button type='button' class='btn btn-info'>No Data Found</button>");
     action = 'active';
    }
    else
    {
     $('#load_data_message').html("<button type='button' class='btn btn-warning'>Please Wait....</button>");
     action = 'inactive';
    }
    
   }
  });
 }


After making of function then after we want to display on data on web page by calling above function, so we have write one if condition which check if action variable value will be inactive then it will execute if block and under this we have called above function and in this block we have also change action variable value will change to active.


if(action == 'inactive')
 {
  action = 'active';
  load_country_data(limit, start);
 }


Then after we have go to PHP page and this page has been received request from Ajax with two variable like limit and start and based on this variable value we will make simple select query which fetch data from table and then after it will convert into HTML format and send back data to Ajax request and Ajax request will display on web page.


<?php
if(isset($_POST["limit"], $_POST["start"]))
{
 $connect = mysqli_connect("localhost", "root", "", "testing");
 $query = "SELECT * FROM tbl_posts ORDER BY post_id DESC LIMIT ".$_POST["start"].", ".$_POST["limit"]."";
 $result = mysqli_query($connect, $query);
 while($row = mysqli_fetch_array($result))
 {
  echo '
  <h3>'.$row["post_title"].'</h3>
  <p>'.$row["post_description"].'</p>
  <p class="text-muted" align="right">By - '.$row["post_author"].'</p>
  <hr />
  ';
 }
}

?>


Now we want to write jquery code when page has been scroll so we have write jquery scroll() event, so when page has been scroll then this event of code will be fire. Under this block we have write if condition which check if height of div tag with $load_data has been greater than windows height and it also check action variable value must be inactive. If this condition will true then it will execute if block and under this block we have first change action variable value must be change to active and we have also increase the start variable value increase by value of limit variable. After this we have called load_country_data(limit, start) function under setTimeout() function for called this function for waiting of one second.


$(window).scroll(function(){
  if($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive')
  {
   action = 'active';
   start = start + limit;
   setTimeout(function(){
    load_country_data(limit, start);
   }, 1000);
  }
 });


So, this is our simple web tutorial on load data while scrolling page down with JQuery Ajax and PHP.

 


Source Code


index.php



<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | Auto Load More Data on Page Scroll with Jquery & PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">
   <h2 align="center">Auto Load More Data on Page Scroll with Jquery & PHP</a></h2>
   <br />
   <div id="load_data"></div>
   <div id="load_data_message"></div>
   <br />
   <br />
   <br />
   <br />
   <br />
   <br />
  </div>
 </body>
</html>
<script>

$(document).ready(function(){
 
 var limit = 7;
 var start = 0;
 var action = 'inactive';
 function load_country_data(limit, start)
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   data:{limit:limit, start:start},
   cache:false,
   success:function(data)
   {
    $('#load_data').append(data);
    if(data == '')
    {
     $('#load_data_message').html("<button type='button' class='btn btn-info'>No Data Found</button>");
     action = 'active';
    }
    else
    {
     $('#load_data_message').html("<button type='button' class='btn btn-warning'>Please Wait....</button>");
     action = "inactive";
    }
   }
  });
 }

 if(action == 'inactive')
 {
  action = 'active';
  load_country_data(limit, start);
 }
 $(window).scroll(function(){
  if($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive')
  {
   action = 'active';
   start = start + limit;
   setTimeout(function(){
    load_country_data(limit, start);
   }, 1000);
  }
 });
 
});
</script>






fetch.php



<?php
if(isset($_POST["limit"], $_POST["start"]))
{
 $connect = mysqli_connect("localhost", "root", "", "testing");
 $query = "SELECT * FROM tbl_posts ORDER BY post_id DESC LIMIT ".$_POST["start"].", ".$_POST["limit"]."";
 $result = mysqli_query($connect, $query);
 while($row = mysqli_fetch_array($result))
 {
  echo '
  <h3>'.$row["post_title"].'</h3>
  <p>'.$row["post_description"].'</p>
  <p class="text-muted" align="right">By - '.$row["post_author"].'</p>
  <hr />
  ';
 }
}

?>

43 comments:

  1. Hello, can you convert MySQLi to PDO? thank you

    ReplyDelete
  2. it is work on localhost but when i use it on server it not working

    ReplyDelete
  3. Really. so much helpful. thanks

    ReplyDelete
  4. That was an awesome ! thanks a lot its helpful fir me

    ReplyDelete
  5. Hi This is pravin
    ur tutorial was useful to me.. thnks
    but after i load full content from db it still says 'please wait' it doesn't say 'No record found'

    ReplyDelete
  6. I have some ploblem about this code if show all data in the table this function can not work >>> No Data Found button how to fix it. Thank you.

    ReplyDelete
  7. Hello Sir i am seeing your all video and your all video is very good and support us to increase our knowledge ...I need a help from you that i want 'Load Content while Scrolling with Jquery Ajax PHP' aand price range add together using only singal mysql database used....Please sir help me

    ReplyDelete
  8. Hello Sir i am seeing your all video and your all video is very good and support us to increase our knowledge ...I need a help from you that i want 'Load Content while Scrolling with Jquery Ajax PHP' aand price range add together using only singal mysql database used....Please sir help me

    ReplyDelete
  9. Hello Sir i am seeing your all video and your all video is very good and support us to increase our knowledge ...I need a help from you that i want 'Load Content while Scrolling with Jquery Ajax PHP' aand price range add together using only singal mysql database used....Please sir help me

    ReplyDelete
  10. hello sir i need this complete code in laravel framework, please help me

    ReplyDelete
  11. how can i download jquery libraries you have use please tell me...

    ReplyDelete
  12. thanks for youtube video and code

    ReplyDelete
  13. Thanks. now i have to filter data according to checkbox. how i can do that in it. because when I checked my checkbox its giving me correct data but when i load all the page after it check box not returning me anything due to start variable . because when i scroll down the page start variable value increased.

    ReplyDelete
  14. hi i am loading data when i am doing that all data getting when i clicked on bottom not wait for loading i did diffrent way

    ReplyDelete
  15. Simple Clair Utile , Merci Chapeau

    ReplyDelete
  16. If there is data of only one page and no scroll, then too the button keeps saying "Please Wait...". Is there any solution to hide that button if no scroll?

    ReplyDelete
    Replies
    1. use $('#load_data').append(data); inside of the if function instead of outside

      Delete
  17. Thank you for this post. But I have a problem the urls.

    I want to change the urls after scroll. I mean the last post urls sholud seem the urls but the first urls seem all the time How can ı figure it out this problem ?

    Thenk you from now on

    ReplyDelete
  18. Yes. even in 2020 the code still works! Thanks

    ReplyDelete
  19. Please how do you hide loader when all data has been fetched or displayed on the screen. because its still showing Please Wait....

    ReplyDelete
  20. here i give solution for always displayed "Please Wait..."
    use !$.trim(data) for checking data empty or not, or change from if(data == '') to if(!$.trim(data)), this will solve the problem

    ReplyDelete
  21. Can you help me???
    My project had displayed but not load database ( had displayed Please wait.....)

    ReplyDelete
  22. This works perfectly for me. Thank you

    ReplyDelete