Load more results with jQuery AJAX and PHP

You can use just one “Load More” button on your website to show a list of things. It’s a common way to organize information on websites and mobile apps. People click the button when they want to see more items.

When you click the button, more items will be added to the list you already see.

In this tutorial, I am creating a similar type of functionality using jQuery and AJAX.

Load more results with jQuery,AJAX, and PHP


Table of Content

  1. Table structure
  2. Create a Database connection file
  3. HTML – Create Load more layout
  4. Add CSS
  5. AJAX file – Return Load more data
  6. jQuery – Handle Load more
  7. Demo
  8. Conclusion

1. Table structure

I am using posts table in the tutorial example.

CREATE TABLE `posts` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  `link` varchar(255) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

2. Create a Database connection file

Create a config.php for the database connection.

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);

// Check connection
if (!$con) {
   die("Connection failed: " . mysqli_connect_error());
}

3. HTML – Create Load more layout

First, count the total number of posts and selecting the first 3 posts from the posts table.

Create a post structure by looping through the fetch data.

Created two hidden fields –

  • First, one stores the current row position. and
  • The total number of rows is stored in another field.

In jQuery, use these fields to show new posts.

Also, created a <h2> element with text Load more. When the click event trigger on it then fetch new posts using jQuery AJAX.

<?php
include "config.php";
?>
<!doctype html>
<html>
    <head>
        <title>Load more data using jQuery,AJAX, and PHP</title>
        <link href="style.css" type="text/css" rel="stylesheet">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
        <script src="script.js"></script>
    </head>
    <body>
        <div class="container">

            <?php
            $rowperpage = 3;

            // counting total number of posts
            $allcount_query = "SELECT count(*) as allcount FROM posts";
            $allcount_result = mysqli_query($con,$allcount_query);
            $allcount_fetch = mysqli_fetch_array($allcount_result);
            $allcount = $allcount_fetch['allcount'];

            // select first 5 posts
            $query = "select * from posts order by id asc limit 0,$rowperpage ";
            $result = mysqli_query($con,$query);

            while($row = mysqli_fetch_array($result)){

                $id = $row['id'];
                $title = $row['title'];
                $content = $row['content'];
                $shortcontent = substr($content, 0, 160)."...";
                $link = $row['link'];
            ?>

                <div class="post" id="post_<?php echo $id; ?>">
                    <h2><?php echo $title; ?></h2>
                    <p>
                        <?php echo $shortcontent; ?>
                    </p>
                    <a href="'.$link.'" target="_blank" class="more">More</a>
                </div>

            <?php
            }
            ?>

            <h2 class="load-more">Load More</h2>
            <input type="hidden" id="row" value="0">
            <input type="hidden" id="all" value="<?php echo $allcount; ?>">

        </div>
    </body>
</html>

4. Add CSS

.container{
    width: 55%;
    margin: 0 auto;
    border: 0px solid black;
    padding: 10px 0px;
}

/* post */
.post{
    width: 97%;
    min-height: 200px;
    padding: 5px;
    border: 1px solid gray;
    margin-bottom: 15px;
}

.post h2{
    letter-spacing: 1px;
    font-weight: normal;
    font-family: sans-serif;
}


.post p{
    letter-spacing: 1px;
    text-overflow: ellipsis;
    line-height: 25px;
}

/* Load more */
.load-more{
    width: 99%;
    background: #15a9ce;
    text-align: center;
    color: white;
    padding: 10px 0px;
    font-family: sans-serif;
}

.load-more:hover{
    cursor: pointer;
}
/* more link */
.more{
    color: blue;
    text-decoration: none;
    letter-spacing: 1px;
    font-size: 16px;
}

5. AJAX file – Return Load more data

Create a file called getData.php to handle AJAX requests. Retrieve the next 3 post records from the posts table based on the value in $_POST['row'].

After fetching the data, generate a string variable that holds the HTML layout for these posts. This string variable will be returned as the response to the AJAX request.

<?php

// configuration
include 'config.php';

$row = $_POST['row'];
$rowperpage = 3;

// selecting posts
$query = 'SELECT * FROM posts limit '.$row.','.$rowperpage;
$result = mysqli_query($con,$query);

$html = '';

while($row = mysqli_fetch_array($result)){
    $id = $row['id'];
    $title = $row['title'];
    $content = $row['content'];
    $shortcontent = substr($content, 0, 160)."...";
    $link = $row['link'];
    // Creating HTML structure
    $html .= '<div id="post_'.$id.'" class="post">';
    $html .= '<h2>'.$title.'</h2>';
    $html .= '<p>'.$shortcontent.'</p>';
    $html .= '<a href="'.$link.'" target="_blank" class="more">More</a>';
    $html .= '</div>';

}

echo $html;

6. jQuery – Handle Load more

Send AJAX request when <h2 class='load-more'> gets clicked and Passing new row index as data in AJAX.

On successful callback append the response to the last of the .post class element and generate the next row index position, if the value is greater than allcount then change the <h2> element text to Hide.

If the new row index value is greater than allcount value (total number of rows) then removing the all .post elements except for the first 3 elements and change <h2> element text to Load more.

Note – Here I only use setTimeout() method to add some delay while displaying data.

$(document).ready(function(){

    // Load more data
    $('.load-more').click(function(){
        var row = Number($('#row').val());
        var allcount = Number($('#all').val());
        var rowperpage = 3;
        row = row + rowperpage;

        if(row <= allcount){
            $("#row").val(row);

            $.ajax({
                url: 'getData.php',
                type: 'post',
                data: {row:row},
                beforeSend:function(){
                    $(".load-more").text("Loading...");
                },
                success: function(response){

                    // Setting little delay while displaying new content
                    setTimeout(function() {
                        // appending posts after last post with class="post"
                        $(".post:last").after(response).show().fadeIn("slow");

                        var rowno = row + rowperpage;

                        // checking row value is greater than allcount or not
                        if(rowno > allcount){

                            // Change the text and background
                            $('.load-more').text("Hide");
                            $('.load-more').css("background","darkorchid");
                        }else{
                            $(".load-more").text("Load more");
                        }
                    }, 2000);

                }
            });
        }else{
            $('.load-more').text("Loading...");

            // Setting little delay while removing contents
            setTimeout(function() {

                // When row is greater than allcount then remove all class='post' element after 3 element
                $('.post:nth-child(3)').nextAll('.post').remove();

                // Reset the value of row
                $("#row").val(0);

                // Change the text and background
                $('.load-more').text("Load more");
                $('.load-more').css("background","#15a9ce");
                
            }, 2000);


        }

    });

});

7. Demo

View Demo


8. Conclusion

Load the records using jQuery AJAX when the load more button gets clicked. The process goes on until all list of data is not shown.

If you prefer, you can choose to remove the “Hide” button that appears when the user reaches the end, eliminating the option for the user to hide the list.

If you found this tutorial helpful then don't forget to share.