Ajax & jQuery


Hello folks,
You might have seen the feature of Load More. If you want to develop such a feature as “Load more data using jQuery” then you are in right place. You check this demo also before starting to code.

It can be for anything like load more products if you are in e-commerce website, It can be load more post you are visiting any blog website or in general, it can be load more records.
It’s a kind of pagination, yes but it will have a Load More button instead pagination links or page numbers. We will talk about other pagination as well in the upcoming article. For now, we will develop this as a Load more option. However, if you want to check we already have a similar article.

Check Also: How to integrate data table plugin in HTML and CSS

DataTable is a plug-in for the jQuery JavaScript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any HTML table

In this post, we are going to implement a kind of pagination called Load More. We will load Quotes. 
By default, we will load 2 quotes in this example but you can define the number in the constant file or customize this solution as per your requirement.

Now when you click on the Load more button it will load another 2 quotes and append them to the current list. This process will go so on and so far until there are no remaining quotes. The load more button will be hidden if there are no more quotes remaining to load. So let’s start to develop load more data using jQuery, and AJAX.

Step 1: Database Setup

Since we are fetching all quotes/records from the database first of all we need to set up the database. Create a database, and create a table “bird_quotes” because we take this table name in code. In the next section, you will get the SQL query for the same.

Step 2: Code & Files setup

Now we need to create these files as shown in the below screenshot, I will explain the purpose of these files. Now let’s create code for each file and understand the purpose also.

Step 3: Lets code


The purpose of creating this is to store database credentials & pagination settings. In the third part of this article, we considered loading 2 records each time. So this number can be changed from the constant.php file

 * Database configuration
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'codingbirds');

 * Define no. of records to be load each time
define('PER_PAGE', 2);


This file is a PHP class of database connection. As you know we require a database connection with PHP, So here is the code for this file.

include_once "constants.php";
class Database
     * @var mysqli
    public $connection;

    public function __construct()
        $this->connection = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME);
        if (!$this->connection) {
            die("Error in database connection". $this->connection->connect_error);


This index.php is the main file that gets loaded and shows the 2 quotes by default and shows “ajax load more” button UI. Below is the code for this file.

<!doctype html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="icon" href="" type="image/x-icon">
    <link rel="stylesheet" href="">
    <link rel="stylesheet" href="">
    <script src=""></script>
    <script type="text/javascript" src=""></script>
    <title>How to load more records using php, mysql & AJAX - Coding Birds Online</title>
    <style> .blockquote  { font-size: 1.1rem !important; }</style>
<div class="container">
   <div class="mt-3 mb-3">
           <img src="" width="50"/>
    <div class="row">
        <div class="col-sm-9 col-md-7 col-lg-5 mx-auto">
            <div id="quotes-container"></div>
            <input type="hidden" id="page" value="0"/>
                class="btn btn-sm btn-success btn-block"
                >Load more...
                <div id="loading" class="spinner-border spinner-border-sm d-none" role="status">
                    <span class="sr-only">Loading...</span>
    <div class="row">
        <script async src=""></script>
        <!-- middle-ads -->
        <ins class="adsbygoogle"
            (adsbygoogle = window.adsbygoogle || []).push({});
<script src="load-more-quotes.js"></script>


This file contains JavaScript & jQuery logic to load more data. loadMoreQuotes( ) function is called the first time automatically when the page load, later it is called with the click of a button.

     * Call load quotes as soon as page ready
function loadMoreQuotes(){
    let page = parseInt($("#page").val());
    page = page + 1;
    let quotesHtml = ``;
        url: "load-more-script.php",
        method: "POST",
        data: {
            request_name: "load-more-quotes",
            page: page,
        beforeSend: function(){
             * Show the loading icon in load more button
        success: function (response){
             * Prepare the html of quotes
             * @type {any}
            response = JSON.parse(response);
            let quotes =;
            if(quotes.length > 0) {
                $.each(quotes, function (key, value) {
                    quotesHtml += `<div class="card card-signin my-3">
                                    <div class="card-body">
                                        <blockquote class="blockquote mb-0">
                                            <footer class="blockquote-footer">Someone famous in <cite title="Source Title">${}</cite></footer>
                 * Update the page page number to track the no. of calls
                 * Append quotes html prepared to div
                 * Conditionally show/hide the load more button
                if (response.remaining_quotes == 0) {
        error: function(errorResponse){
        complete: function(){
             * Hide loading icon each time when api call completes


This file is a PHP script file to perform our load more pagination from the backend. It returns the response in the form of JSON.

require_once "constants.php";
require_once "Database.php";
require_once "Quote.php";
 * Prepares the Database, Quote class objects
$db = new Database();
$quote = new Quote();
if (isset($_POST['request_name'])){
    if($_POST['request_name'] == 'load-more-quotes'){
         * Make the offset, limit
        $offset = ($_POST['page'] - 1) * PER_PAGE;
        $limit = PER_PAGE;
        $quotesData = array();
        $pagination = array(
            'offset' => $offset,
            'limit' => $limit,
        $quotes = $quote->loadQuotes($db->connection, $pagination);
        $totalQuotes = $quote->totalQuotes($db->connection);
            while ($quote = $quotes->fetch_object()){
                $quotesData[] = $quote;
        echo json_encode(array(
            'data' => $quotesData,
            'remaining_quotes' => $totalQuotes - PER_PAGE * $_POST['page'],


This is a PHP class file which two functions to load the quotes and count total quotes respectively.

class Quote
     * Load the quotes based on limit. offset
     * @param $connection
     * @param $pagination
     * @return object
    public function loadQuotes($connection, $pagination)
        $query = "SELECT * FROM bird_quotes LIMIT ". $pagination['offset']. ",". $pagination['limit'];
        $result = $connection->query($query) or die("Error in query".$connection->error);
        return $result;

     * Calculates the total quotes in database
     * @param $connection
     * @return int
    public function totalQuotes($connection)
        $query = "SELECT COUNT(*) FROM bird_quotes as quotes_count";
        $result = $connection->query($query) or die("Error in query".$connection->error);
        return $result->fetch_row()[0];

SQL code to create table

-- phpMyAdmin SQL Dump
-- version 5.0.4
-- Host:
-- Generation Time: Aug 10, 2022 at 08:44 AM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.4.15

SET time_zone = "+00:00";

/*!40101 SET NAMES utf8mb4 */;

-- Database: `codingbirds`

-- --------------------------------------------------------

-- Table structure for table `bird_quotes`

CREATE TABLE `bird_quotes` (
  `id` int(11) NOT NULL,
  `quote` text NOT NULL,
  `author` varchar(100) NOT NULL

-- Dumping data for table `bird_quotes`

INSERT INTO `bird_quotes` (`id`, `quote`, `author`) VALUES
(1, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(2, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(3, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(4, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(5, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(6, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(7, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(8, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(9, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title'),
(10, 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Source Title');

-- Indexes for dumped tables

-- Indexes for table `bird_quotes`
ALTER TABLE `bird_quotes`

-- AUTO_INCREMENT for dumped tables

-- AUTO_INCREMENT for table `bird_quotes`
ALTER TABLE `bird_quotes`


Step 4: Run the code

Congrats! now you have reached the final step to run the code & get your desired output. As you navigate this localhost URL to your browser you will get something like as below.

Now if you want to load more quotes, just click on the button you will get 2 more quotes without page refresh since we are using AJAX. Why 2 quotes because we defined this value in the constants.php file, you can change it according to your needs.

Source Code & Demo

You can download the full 100% working source code from here. You check this demo also before starting to code.


I hope you learned what I explained in the above steps, If you have any suggestions are appreciated. And if you have any errors comment here, I will help. You can download the full 100% working source code from here.

Ok, Thanks for reading this article, see you in the next post. If this code works for you, please leave a comment so that others can find it useful which gives me the motivation to create such content.