Load more results with jQuery,AJAX, and PHP

You can use a single load more button on your webpage to paginate the list of records.

This type of pagination is very common on the website or in mobile apps.

The user needs to click on the load more button whenever the need to view more items.

After the click, the data will append with the existing list items.

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

Load more results with jQuery,AJAX, and PHP


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. CSS
  5. PHP
  6. jQuery
  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
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a config.php for the database connection.

Completed Code

<?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

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.

Using both these fields in jQuery for displaying 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.

Completed Code

<?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.5.1/jquery.min.js" type="text/javascript"></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. 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. PHP

Create a new getData.php file.

Fetch the next 3 posts records from the posts table on the basis of $_POST['row'] values and return string variable which has HTML layout.

Completed Code

<?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

Sending 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.

Completed Code

$(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.

You can remove the Hide button which shown when the user reaches the end if you don’t want the user to hide the list.

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

11 thoughts on “Load more results with jQuery,AJAX, and PHP”

  1. My friend, the script is great and i will use it. thank you for that.

    But i have a problem with the way I want to use it. i want to show 3 elements in each row, and when i press load more, i want to get 3 new elements. I managed to make the first 3 to appear, but when i press load more, it does not shows them the right way. the one under the other. I am also adding bootstrap col-md-4 to each element, so as to get them 3 for each row and it keeps geting worse and worse. can u help me plzzzz???
    thank you in advance.

    Reply
  2. Remove row + rowperpage; this line from ajax, once set response after you should write this line like this :
    $(“.post:last”).after(response).show().fadeIn(“slow”);
    row = row + rowperpage;
    var rowno = row + rowperpage;

    Reply

Leave a Comment