PHP Ajax Load More on Scroll Example

Mar 22, 2022 . Admin



Hello dev,

I am going to explain you how to PHP Ajax load more on scroll example. You will learn load more data on page scroll using ajax jquery PHP. In side this article we will see ajax load more on scroll in PHP.

This article will give you simple example of load content while scrolling with Jquery Ajax PHP. We will use get simple How to load dynamic data on page scroll with PHP and AJAX.

I will give you simple Example of How to Ajax load more on scroll in PHP.

So, let's see bellow solution:

index.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>PHP Ajax Load More on Scroll Example - Mywebtuts.com</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style type="text/css">
        .loader {
            display:inline-block;
            border: 5px dotted lightgray;
            border-radius: 50%;
            border-top: 5px solid gray;
            border-bottom:5px solid gray;
            width: 30px;
            height: 30px;
            -webkit-animation: spin 1s linear infinite; /* Safari */
            animation: spin 1s linear infinite;
        }

        @-webkit-keyframes spin {
          0% { -webkit-transform: rotate(0deg); }
          100% { -webkit-transform: rotate(360deg); }
        }

        .loader-symbol{
        text-align:center}

        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container mt-5 mb-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card w-75 m-auto">
                    <div class="card-header text-center bg-primary text-white">
                        <h4>PHP Ajax Load More on Scroll Example - Mywebtuts.com</h4>
                    </div>
                    <div class="card-body">
                        <?php
                            require_once('load.php');
                            echo $displayDefaultData;
                        ?>                          
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(document).ready(function(){
            $(window).on('scroll',function(){
                var lastId = $('.loader').attr('id');

                if(($(window).scrollTop() == $(document).height() - $(window).height()) && (lastId != 0)){
                    load_more_data(lastId);
                }
            });

            function load_more_data(lastId){
                $.ajax({
                    type:'GET',
                    url:'load.php',
                    dataType:'html',
                    data:{last_id:lastId},
                    beforeSend:function(){
                        $('.loader').show();
                    },
                    success:function(data){
                        setTimeout(function() {
                        $('.loader').remove();
                        $('#load-content').append(data);
                        },1000);
                    }
                });
            }
        });
    </script>
</body>
</html>
load.php
<?php
    $hostname     = "localhost";
    $username     = "root";
    $password     = "";
    $databasename = "demos";

    $conn = new mysqli($hostname, $username, $password,$databasename);

    if ($conn->connect_error) { 
        die("Unable to Connect database: " . $conn->connect_error);
    }

    $db= $conn; 
    $tableName='blogs'; 
    $limit=1;

    $fetchDefaultData=fetch_default_data($limit,$tableName);
    $displayDefaultData= display_data($fetchDefaultData);

    if(isset($_GET['last_id']) && !empty($_GET['last_id']) ){
        $lastId= validate($_GET['last_id']);
        $fetchMoreData=fetch_more_data($lastId,$limit,$tableName);
        echo display_data($fetchMoreData);
    }

    function validate($value) {
        $value = trim($value);
        $value = stripslashes($value);
        $value = htmlspecialchars($value);
        return $value;
    }

    function fetch_more_data($lastId,$limit,$tableName){
        global $db;
        $limit= trim($limit);
        $tableName=trim($tableName);

        if(empty($limit)){
            return "Limit must be required";
        }elseif (empty($tableName)) {
            return "Database must be required";
        }else{
            $query = $db->prepare("SELECT * FROM ".$tableName." WHERE id< ? ORDER BY id ASC LIMIT ?");

            if($query){
                $query->bind_param('ii',$lastId,$limit);  
                $query->execute();
                $result=$query->get_result();

                if($result){
                    if($result->num_rows>0){
                        $row= $result->fetch_all(MYSQLI_ASSOC);
                        return $row; 
                    }
                }else{
                    return "Error: " . $query . "<br>" . $db->error;
                }
            }else{
                return "Error: " . $query . "<br>" . $db->error;
            }
        }
    }

    function display_data($displayData){

        if(is_array($displayData)){

            $text='';
            $text='<div class="display-content" id="load-content">';

            foreach($displayData as $data){
                $text.= "<div class='record'>";
                $text.= "<h3>".$data['title']."</h3>";
                $text.= "<p>".$data['description']."</p>";
                $text.= "</div>";
            }

            $text.="<div class='loader-symbol'><div class='loader' id='".$data['id']."' style='display: none;'></div></div>";
            $text.="</div>";
            return $text;

        }else{
            return $displayData;
        }
    }

    function fetch_default_data($limit,$tableName){
        global $db;
        $limit= trim($limit);
        $tableName=trim($tableName);

        if(empty($limit)){
            return "Limit must be required";
        }elseif (empty($tableName)) {
            return "Database must be required";
        }else{
            $query = $db->prepare("SELECT * FROM ".$tableName." ORDER BY id DESC LIMIT ?");
      
            if($query){
                $query->bind_param('i',$limit); 
                $query->execute();
                $result=$query->get_result();

                if($result){
                    if($result->num_rows>0){
                        $row= $result->fetch_all(MYSQLI_ASSOC);
                        return $row; 
                    } else{
                        return "No Records Found";
                    }     
                }else{ 
                    return "Error: " . $query . "<br>" . $db->error;
                }
            }else{
                return "Error: " . $query . "<br>" . $db->error;
            }
        }
    }
?>
Output:

It will help you...
#PHP