How to Load Data On Scrolling Page Down using jQuery and PHP

Rumman Ansari   2022-12-07   Developer   web development > How to Load Data On Scrolling Page Down using jQuery and PHP   254 Share

In this blog you will learn How to Load Data On Scrolling Page Down using jQuery & PHP

Prerequisites Section:

You need to have knowledge of HTML, CSS or Bootstrap 5.

You need to have knowledge of JavaScript or jQuery. Because here we used jQuery.

You need to have knowledge of PHP and AJAX.

You need to have knowledge of MySQL database.

HTML & CSS Section:

In this section we will load data.

 
<div id="prependHere">

</div>
 

When we will load the data before loading this spinner will be show to the user.

 
<div class="container d-flex justify-content-center"> 
            <div class="spinner-border m-5 text-danger" id = "loading" role="status">
              <span class="visually-hidden">Loading...</span>
            </div>
 </div>
 

JavaScript section:

Code in the script section. Remember that you should add ajax and jQuery library file before using it.

 
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
// code for scroll data load start

var page_no = 1;
var isrunning = false;
showdata();
$(window).scroll(function(){
    if($(window).scrollTop()+$(window).height() > $(document).height()-50){
        if(!isrunning){
            showdata();
        }
    }
}); 

function showdata(){
    isrunning = true;
    $("#loading").show();
    var functionID = 'partial_fetch';
    $.post("ajax/userPosts.php",{page:page_no, functionID:functionID},(response)=>{
        if(response){
            $("#prependHere").append(response);
            $("#loading").hide();
            isrunning = false;
            page_no++;
        }else{
            $("#loading").hide(); 
        }
    });
}

// code for scroll data load end 
 

AJAX PHP Section:

You can write the below code to show data to user.

 
function partial_fetch(){
    sleep(2);
  $page = $_POST['page']??1;
  $limit = 5;
  $rowno = ($page - 1)*$limit;

  $query = "SELECT * FROM post limit $rowno, $limit";  
  $result = query($query, 'select'); 
  foreach($result as $key => $row){ ?>
      <div class="card">
      <div class="card-header">Post Header</div>
      <div class="card-body"> <?php echo $row['post_title']; ?> </div>
      <div class="card-footer">Post  Footer</div>
     </div>
     <?php
  }

}