CodeIgniter 4 Ajax jQuery Load More Data on Page Scroll

Last Updated on by in CodeIgniter

Codeigniter Ajax Load more data on page scroll tutorial; Throughout this comprehensive guide, you will find out how to easily integrate load more data on-page or window scroll with the help of jQuery Ajax in Codeigniter 4 application.

To spruce up the user interface, we will use the dynamic bootstrap 5 CSS framework.

User experience is the top priority of the web and mobile applications; theoretically, to make the ux commemorative, we try to implement various variations in the ui.

The most famous ui strategy is nowadays is to display data on or load more data on page scroll; the great thing about load more data is you don’t bother to reload the entire web page.

This Codeigniter 4 jQuery ajax load more data tutorial will explain how to show more data or load data on page scroll and display in the view.

Facebook, Twitter, Tumblr, Instagram, LinkedIn and other innumerable software applications where you can load data on a scroll or scroll up for the infinite times; this way, the user engagement increases and makes the user love the application.

How to Load Data on Page Scroll in CodeIgniter 4 using Ajax jQuery

  • Step 1: Install New Codeigniter App
  • Step 2: Commission Error Handling
  • Step 3: Create Table and Insert Data
  • Step 3: Connect to Database
  • Step 4: Set Up Model
  • Step 5: Create Ajax Load More Controller
  • Step 6: Define Route
  • Step 7: Set Up Load More Views
  • Step 8: Start CI Project

Install New Codeigniter App

If you have composer set up on your system, execute the create-project command to install the archetype of the CodeIgniter app.

composer create-project codeigniter4/appstarter

Change the app folder name as per your choice.

There is another easy and fast method, and you can download the Codeigniter app directly from the official website.

Commission Error Handling

While developing an application, seldom we need to debug the errors. Consequently, you have to enable the display_errors, get inside the app/Config/Boot/development.php likewise app/Config/Boot/production.php file and set the display_errors prop to 1 from 0.

ini_set('display_errors', '1');

Create Table and Insert Data

To load the data on scroll requires to have the database set up, the table created with the test data.

If you haven’t done this create the database, create the new table and pour test data into it, run SQL command from the PHPMyAdmin dashboard.

CREATE TABLE users (
    id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
    name varchar(100) NOT NULL COMMENT 'Name',
    email varchar(255) NOT NULL COMMENT 'Email',
    designation varchar(255) NOT NULL COMMENT 'Designation',
    created_at varchar(30) NOT NULL COMMENT 'Created Date',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable users table' AUTO_INCREMENT=1;
 
 
INSERT INTO users(id, name, email, designation, created_at) VALUES
  (1, 'Irma L. Murphy', 'irma@gmail.com', 'Sales', '2021-02-02'),
  (2, 'Chris L. Ellis', 'ellis@yahoo.com', 'Marketing', '2020-03-03'),
  (3, 'Cameron C. Finley', 'cameron@rediff.com', 'Human Resource', '2019-01-05'),
  (4, 'Howard C. Schlueter', 'schlueter@gmail.com', 'Admin', '2018-05-02'),
  (5, 'Robert N. Alloway', 'alloway@gmail.com', 'Social Media Manager', '2017-05-11'),
  (6, 'Marian A. Rosado', 'marian@gmail.com', 'Web Developer', '2016-05-012'),
  (7, 'Maria L. Leal', 'maria@yahoo.com', 'UI Designer', '2016-04-11'),
  (8, 'Amber M. Schneider', 'schneider@rediff.com', 'Finance', '2016-03-04'),
  (9, 'Robert K. Jordan', 'jordan@gmail.com', 'Sales', '2016-02-03'),
  (10, 'Michael E. Jones', 'michael@yahoo.com', 'IT Head', '2015-03-15'),
  (11, 'Alicia T. Sosa', 'alicia@gmail.com', 'Marketing', '2015-06-12'),
  (12, 'Larry P. Melton', 'melton@yahoo.com', 'Sales', '2015-05-15');

Connect to Database

Open app/Config/Database.php file inside the public default array, include the database name, username, and password for connecting the CI app to the MySQL database.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'codeigniter_db',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];

CodeIgniter\Database\Exceptions\DatabaseException

Sometimes, Unable to connect database : Codeigniter error might manifest on the app screen.

Preferably if you are using either MAMP or XAMP local servers. In that case, you may replace the hostname property based on the local server that you are using.

# XAMP
public $default = [
  ...
  ...
  
  'hostname' => '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',
]

# MAMP
public $default = [
  ...
  ...
     
  'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',
]

Set Up Model

In this section, get into the app/Models folder, create the User.php file.

After that, open the app/Models/User.php file and add the following code and save the file.

<?php 
namespace App\Models;

use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
 
class User extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'email'];
}

Create Ajax Load More Controller

This step commands you to get to the app/Controllers folder, then create AjaxLoadMore.php file.

Furthermore place the suggested code inside the app/Controllers/AjaxLoadMore.php file.

In this file, we are getting the users’ data page wise from the database, and we will use ajax to make the request and display it on page scroll.

<?php
namespace App\Controllers; 
use CodeIgniter\Controller;
use App\Models\User;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

 
class AjaxLoadMore extends Controller {  
 
    public function index() {
        helper(['form', 'url']);
 
        $this->modelUser = new User();
 
        $data = [
            'users' => $this->modelUser->paginate(3),
            'pager' => $this->modelUser->pager
        ];
        
        return view('index', $data);
    }
 
   public function loadMoreUsers(){
        $limit = 3; 
        $page = $limit * $this->request->getVar('page');
        $data['users'] = $this->fetchData($page);

        return view('load_more', $data);
   }
   
   function fetchData($limit){
        $db = new User();
 
        $dbQuery = $db->select('*')->limit($limit)->get();
        return $dbQuery->getResult();
   }
 
}

Define Route

In this step, we need to define the new route for displaying the view file with the load more data.

Open and update the code inside the app/Config/Routes.php file.

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
*/


$routes->get('/', 'AjaxLoadMore::index');
$routes->match(['get', 'post'], 'AjaxLoadMore/loadMoreUsers', 'AjaxLoadMore::loadMoreUsers');
$routes->match(['get', 'post'], 'AjaxLoadMore/fetchData', 'AjaxLoadMore::fetchData');

Set Up Load More Views

Ultimately, in the final step, we need to get into the app/Views folder and create two files (index.php and load_more.php).

One file will hold the loaded data, and another is the archetype where we get the users data and display it on the view and also load more data on page scroll.

Update app/Views/index.php file:

<!DOCTYPE html>
<html>

<head>
    <title>Codeigniter 4 Ajax Load More on Page Scroll Example</title>
</head>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css">

<style type="text/css">
    body {
        font-size: 20px;
        color: #333;
        min-height: 1500px;
    }
    .container {
        margin: 50px auto 0;
        max-width: 550px;
    }
    .card {
        background: #12c2e9;
        background: -webkit-linear-gradient(to right, #f64f59, #c471ed, #12c2e9);
        background: linear-gradient(to right, #f64f59, #c471ed, #12c2e9);
        width: 100%;
        padding: 2.5em;
        margin: 0 0 25px;
        border-radius: 12px;
    }
</style>

<body>
    <div class="container">
        <?php if($users): ?>
            <?php foreach($users as $user): ?>
                <div class="card">
                   <strong><?php echo $user['name']; ?></strong>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>

        <div id="main"></div>
    </div>
</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>
    var SITEURL = "<?php echo base_url(); ?>";
    var page = 1;
    var isDataLoading = true;
    var isLoading = false;

    $(window).scroll(function () {
        if ($(window).scrollTop() + $(window).height() >= $(document).height() - 500) {
            if (isLoading == false) {
                isLoading = true;
                page++;
                if (isDataLoading) {
                    load_more(page);
                }
            }
        }
    });

    function load_more(page) {
        $.ajax({
            url: SITEURL+"/AjaxLoadMore/loadMoreUsers?page=" + page,
            type: "GET",
            dataType: "html",
        }).done(function (data) {
            isLoading = false;
            if (data.length == 0) {
                isDataLoading = false;
                $('#loader').hide();
                return;
            }
            $('#loader').hide();
            $('#main').append(data).show('slow');
        }).fail(function (jqXHR, ajaxOptions, thrownError) {
            console.log('No response');
        });
    }
</script>

</html>

Update app/Views/load_more.php file:

<?php if($users): ?>
<?php foreach($users as $user): ?>
<div class="card">
    <strong><?php echo $user->name; ?></strong>
</div>
<?php endforeach; ?>
<?php endif; ?>

Start CI Project

Next, use the php spark serve command to serve the Codeigniter development server:

php spark serve

Open the browser and run the following url to test the app.

http://localhost:8080

Conclusion

So, this was it; eventually, the Codeigniter 4 ajax load more example is over; we hope you have comprehended the entire process and understood how to load more data without page refresh in the Codeigniter app.