Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

CodeIgniter 4 Ajax jQuery Load More Data on Page Scroll Tutorial

Last Updated on August 2, 2024 by

jQuery AJAX will help developers to create a feature to load data dynamically on page scroll using jQuery AJAX in CodeIgniter 4 projects without refreshing the web page.

Let’s show you how to create a feature in a CI project to dynamically load more data on page scroll using jQuery AJAX:

Step 1: Set Up Codeigniter 4

Visit official website of codeIgniter: https://codeigniter.com/download, and download CodeIgniter zip file. And extract this file in xampp/htdocs directory.

Step 2: Create Table in DB

Run the following sql queries to create a table in database and insert a dummy data in it:

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 Address',
    contact_no varchar(50) NOT NULL COMMENT 'Contact No',
    created_at varchar(20) NOT NULL COMMENT 'Created date',
    PRIMARY KEY (id)
  ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=1;
INSERT INTO users(id, name, email, mobile_number, created_at) VALUES
  (1, 'Team', '[email protected]', '9000000005', '2024-05-05'),
  (2, 'Admin', '[email protected]', '9000000002', '2024-05-02'),
  (3, 'User', '[email protected]', '9000000003', '2024-05-03'),
  (4, 'Editor', '[email protected]', '9000000004', '2024-05-04'),
  (5, 'Writer', '[email protected]', '9000000005', '2024-05-05'),
  (6, 'Contact', '[email protected]', '9000000006', '2024-05-06'),
  (7, 'Manager', '[email protected]', '9000000007', '2024-05-07'),
  (8, 'John', '[email protected]', '9000000055', '2024-05-08'),
  (9, 'Merry', '[email protected]', '9000000088', '2024-05-09'),
  (10, 'Keliv', '[email protected]', '9000550088', '2024-05-10'),
  (11, 'Herry', '[email protected]', '9050550088', '2024-05-11'),
  (12, 'Mark', '[email protected]', '9050550998', '2024-05-12');

Step 3: Create Model

In app/models directory create a file named user.php, and add the following code in it:

<?php 
namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
class User extends Model
{
    protected $table = 'users';
    protected $allowedFields = ['name', 'email'];
}

Step 4: Create LoadMoreData Controller

In app/controllers directory, create a controller named LoadMoreData.php controller file, and implement some methods in it to handle ajax load more requests:

<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\User;
class LoadMoreData extends Controller {
    public function index() {
        
        helper(['form', 'url']);
        $this->UserModel = new User();
        $data = [
            'users' => $this->UserModel->paginate(5),
            'pager' => $this->UserModel->pager
        ];
       
        return view('home', $data);
    }
   public function get_ajax_load_more(){
        $limit = 5; 
        $page = $limit * $this->request->getVar('page');
        $data['users'] = $this->get_load_more_data($limit,$page);
        $isExist = return view('load_more_loop', $data);
        if($isExist){
            echo json_encode($isExist);
        }
   } 
   function get_load_more_data($limit, $offset = ''){
        $builder = new User();
        $query = $builder->select('*')
                 ->limit($limit,$offset)
                 ->get();
        return $query->getResult();
   }  
}

Step 5: Create Views

In app/views directory, create file named home.php, and add the following code in it:

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter 4 Ajax Load More on Page Scroll - itcodstuff.com </title>
</head>
<!-- Latest compiled and minified CSS -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
<style type="text/css">
.result {
    background-color: #1fc8db;
    background-image: linear-gradient(141deg, #9fb8ad 0%, #1fc8db 51%, #2cb5e8 75%);
    width: 100%;
    padding: 1em;
    margin: 0.5em;
    -webkit-border-radius: 9px;
    -moz-border-radius: 9px;
    border-radius: 9px;
    border: solid 2px honeydew;
}
</style>
<body>
 <div  class="container">
   <div class="row" id="main">
    <?php if($users): ?>
    <?php foreach($users as $user): ?>
     <div class="result">
      <h2><?php echo $user->name; ?></h2>
     </div>
    <?php endforeach; ?>
    <?php endif; ?>
   </div>
 </div> 
</body>
<script>
   var SITEURL = "<?php echo base_url(); ?>";
   var page = 1; //track user scroll as page number, right now page number is 1
   var is_more_data = true;
   var is_process_running = false;
   $(window).scroll(function() { //detect page scroll
       if($(window).scrollTop() + $(window).height() >= $(document).height() - 1800) { //if user scrolled from top to bottom of the page
         if(is_process_running == false) {
           is_process_running = true;
             page++; //page number increment
             if(is_more_data){
               //$('#loader').show();
                load_more(page); //load content   
             }
         }
          
       }
   });     
   
  function load_more(page){
      
   $.ajax({
       url:  SITEURL+"index.php/loadmoredata/get_ajax_load_more?page=" + page,
       type: "GET",
       dataType: "html",
    }).done(function(data) {
     is_process_running = false;
       if(data.length == 0){
            is_more_data = false;
           //console.log(data.length);
           $('#loader').hide();
           return;
       }
      $('#loader').hide();
       $('#main').append(data).show('slow'); //append data into #results element          
   }).fail(function(jqXHR, ajaxOptions, thrownError){
         alert('No response from server');
   });
  }
</script>
</html>

And create file named load_more_loop.php, and add the following code in it:

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

Step 6: Test Application

Open browser and type http://localhost/demo/public/index.php/loadmoredata url in it to test the application.

Leave a Comment