Codeigniter 4 jQuery Ajax Load More Data on Page Scroll Tutorial

Codeigniter 4 jQuery Ajax Load More Data on Page Scroll Tutorial

If you need to dynamically load the data list on page or button scrolling using jquery ajax without refreshing the whole web page, you can follow this guide. In this tutorial guide, you’ll discover a complete step-by-step on how to dynamically load data or a data list and display the retrieved data to HTML elements when the page or button is scrolled or auto-loaded using jQuery AJAX in codeigniter 4 projects.

Dynamic load data while scrolling the page down with jQuery Ajax and Codeigniter 4 app. In this example, you will learn how to create a dynamic load of more data on page or button scroll using jquery Ajax in Codeigniter 4 with Bootstrap 4.

Codeigniter 4 – Auto Load More Data on page or button scroll using Ajax jQuery and Bootstrap Tutorial

Using the below-given steps, you can easily make dynamic load of more data on page or button scroll using jquery Ajax in Codeigniter 4 with Bootstrap 4:

  • Step 1: Setup Codeigniter Project
  • Step 2: Configure CI Project
  • Step 3: Create a Database and Table
  • Step 4: Setup Database with CI Project
  • Step 5: Create Model File
  • Step 6: Create Controller
  • Step 7: Create Views
  • Step 8: Test App On Browser

Step 1: Setup Codeigniter Project

In this step, you will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new set up and unzip the setup in your local system xampp/htdocs/ . And change the download folder name to “demo”

Step 2: Configure CI Project

Once you have downloaded and set up the ci project in your server. Now you need to set some basic configuration on the app/config/app.php file, so visit application/config/config.php and open this file on text editor. And then set the Base URL like this following:

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Step 3: Create a Database and Table

In this step, you need to create a database name demo, so let’s open your PHPMyAdmin and create the database with the name demo. After successfully create a database, you can use the below SQL query for creating a table in your database.

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]', '9000000001', '2019-01-01'),
  (2, 'Admin', '[email protected]', '9000000002', '2019-01-02'),
  (3, 'User', '[email protected]', '9000000003', '2019-01-03'),
  (4, 'Editor', '[email protected]', '9000000004', '2019-01-04'),
  (5, 'Writer', '[email protected]', '9000000005', '2019-01-05'),
  (6, 'Contact', '[email protected]', '9000000006', '2019-01-06'),
  (7, 'Manager', '[email protected]', '9000000007', '2019-01-07'),
  (8, 'John', '[email protected]', '9000000055', '2019-01-08'),
  (9, 'Merry', '[email protected]', '9000000088', '2019-01-09'),
  (10, 'Keliv', '[email protected]', '9000550088', '2019-01-10'),
  (11, 'Herry', '[email protected]', '9050550088', '2019-01-11'),
  (12, 'Mark', '[email protected]', '9050550998', '2019-01-12');

Step 4: Setup Database with CI Project

In this step, you need to connect our project to the database. you need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, you need to set up database credentials in this file like below.

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

Step 5: Create Model File

In this step, visit app/Models/ and create here one model named User.php. Then add the following code into your User.php file:

<?php namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;

class User extends Model
{
    protected $table = 'users';

    protected $allowedFields = ['name', 'email'];
}

Step 6: Create Controller

In this step, Visit app/Controllers and create a controller name Ajax.php. In this controller, you need to add the following methods into it:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\User;

class Ajax 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 7: Create Views

In this step, you need to create one view files name home.php and update the following code into your file:

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter 4 Ajax Load More on Page Scroll</title>
</head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<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>
      <span>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</span>
     </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/ajax/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>

Next, create load_more_loop.php inside views directory. And add the following code into it:

  <?php if($users): ?>
    <?php foreach($users as $user): ?>
     <div class="result">
      <h2><?php echo $user->name; ?></h2>
      <span>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</span>
     </div>
    <?php endforeach; ?>
    <?php endif; ?>

Step 8: Test App On Browser

Now, Go to the browser and hit below the URL.

http://localhost/demo/public/index.php/ajax

Conclusion

Codeigniter 4 ajax load more example tutorial, you have learned how to load more data using ajax without reloading the web page in Codeigniter 4 app.

Recommended Codeigniter Tutorials

If you have any questions or thoughts to share, use the comment form below to reach us.

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *