This tutorial explains how to load more data while scrolling using ajax and jquery. If we have lot of data, we can not display whole data at one time

that may cause website speed. So we need to display the data in chunks. This script help you to display data in chunks.

Create messages table in mysql:
=======================

Below is the structure of messages table with basic fields. 

 CREATE TABLE `messages` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `message` TEXT NULL,
  `created_at` DATETIME NULL,
  `updated_at` DATETIME NULL,
  PRIMARY KEY (`id`));


Create Connection(config.php) 
=======================

Connect to the database. In config.php add your database name, database username, database password and database name.

<?php
//Database details
$db_host = 'localhost';
$db_username = 'username';
$db_password = 'password';
$db_name = 'database_name';

//Create connection and select DB
$conn = mysqli_connect($db_host, $db_username, $db_password, $db_name);
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

index.php
=======

<?php require_once 'config.php'; ?>
<!--
Used basic html and bootstrap skeleton from the below link for style purpose which contains bootstrap.css,bootstrap.js,jquery.js
https://www.w3schools.com/bootstrap/bootstrap_get_started.asp
Used bootstrap form elements from below link.
https://www.w3schools.com/bootstrap/bootstrap_forms.asp
-->
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Load More Data while Scrolling Page Down with jQuery, Ajax and PHP</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.3.7/css/bootstrap.min.css">
        <style>
            .message_box {
                height: 75px;
                width: 600px;
                border: dashed 1px #48B1D9;
                padding: 5px;
            }
            .load-data-msg{
                font-size: 20px;
                color: #48B1D9
            }
            .msg-number{
                background-color: #48B1D9;
                color: #000;
                padding-left: 3px;
                padding-bottom: 3px;
                padding-right: 3px;
                font-weight: bold;
                font-size: 20px;
                width: 30px;
            }
            #msg_loader{
                position: fixed;
                bottom: 20%;
                left: 38%;
                display: none;
            }
        </style>
    </head>
    <body>
        <div class="container" style="max-width:800px;margin:0 auto;margin-top:50px;">  
            <div>
                <h2 style="margin-bottom:50px;">Live Demo: Load More Data while Scrolling Page Down with jQuery, Ajax and PHP</h2>              
            </div>
            <div style="margin-bottom:20px;">
                <?php
                $sql = mysqli_query($conn, "SELECT * FROM messages ORDER BY id DESC LIMIT 20");
                while ($row = mysqli_fetch_array($sql)) {
                    $msgID = $row['id'];
                    $msg = $row['message'];
                    ?>
                    <div class="load-data-wrap message_box" data-id="<?php echo $msgID; ?>">
                        <div class="load-data-msg"><?php echo $msg; ?></div>
                        <div class="msg-number"><?php echo $msgID; ?></div>
                    </div>
                <?php } ?>
                <div id="msg_loader"><img src="bigLoader.gif"></div>
            </div>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <script>
            $(document).ready(function () {
                $(window).scroll(function () {
                    if ($(window).scrollTop() == $(document).height() - $(window).height()) {
                        var msg_id = $(".message_box:last").data("id");
                        $("#msg_loader").show();
                        $.ajax({
                            type: "POST",
                            url: "fetch.php",
                            data: {msg_id: msg_id},
                            cache: false,
                            success: function (data) {
                                //Insert data after the message_box 
                                $(".message_box:last").after(data);
                                $("#msg_loader").hide();
                            }
                        });

                    }
                });
            });
        </script>
    </body>
</html>


fetch.php
=======

<?php
require_once 'config.php';
if (isset($_POST['msg_id'])) {
    $msg_id = $_POST['msg_id'];
    $sql = mysqli_query($conn, "select * from messages where id < $msg_id order by id desc limit 5");
    while ($row = mysqli_fetch_array($sql)) {
        $msgID = $row['id'];
        $msg = $row['message'];
        ?>
        <div class="load-data-wrap message_box" data-id="<?php echo $msgID; ?>">
            <div class="load-data-msg"><?php echo $msg; ?></div>
            <div class="msg-number"><?php echo $msgID; ?></div>
        </div>
        <?php
    }
} else {
    echo "Message ID is empty";
}
?>
Written by
Check out this Author's contributed articles.
If you like Tutorialsmint and would like to contribute, you can also write an article using Write an Article. See your article appearing on the Tutorialsmint main page and help other programmers to enhance their knowledge.

Comments(0)

RECENT TUTORIALS
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Edit Post
Add Reply