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

Load data while scrolling page down with jQuery Ajax and Codeigniter 4; In this tutorial, i will show you how to implement Load data while scrolling page down using Ajax , jQuery, Mysql and Bootstrap 4 library and Codeigniter 4.

For build dynamic load more data from database using jquery ajax php mysql in codeigniter 4 app, you have to use Ajax jQuery with Codeigniter 4 framework. So in this example, you have make dynamic load more data from database using jquery ajax php mysql in codeigniter 4. Here you can find step by step guide for build how to create dynamic load more data from database using jquery ajax php mysql in codeigniter 4.

Loading data while scrolling down the page using Ajax, jQuery, Mysql and Bootstrap 4 libraries in Codeigniter 4 is the most well-known UI strategy nowadays; The best part about loading more data is that you don’t need to reload the entire web page. This Codeigniter 4 jQuery Ajax Load More Data tutorial; I will show you how to show more data or load data on page scroll and display in view using ajax, jquery, mysql and bootstrap 4 library in codeigniter 4.

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

Use the below given steps to load data on page scroll in CodeIgniter 4 using jQuery ajax:

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Create Database and Table
  • Setup Database Credentials
  • Create Controller
  • Create Views
  • Setup Routes
  • Start Development server

Step 1 – Install Codeigniter 4 Application

First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

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

Step 3 – Create Database and Table

Create a database and users table by executing the following SQL query. And as well as, insert data into these tables:

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 Credentials

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'test',
        'password' => '4Mu99BhzK8dr4vF1',
        'database' => 'demo',
        '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,
	];

Step 5 – Create Model and Controller

Create UserModel.php file. So, visit app/Modelsdirectory and create UserModel.php.Then add the following code into it:

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

class UserModel extends Model
{
    protected $table = 'contacts';

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

Create AjaxLoadMore.php file. So, visit app/Controllers directory and create AjaxLoadMore.php.Then add the following code into it:

<?php

namespace App\Controllers;

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

class AjaxLoadMore extends Controller {


    public function index() {
        
        helper(['form', 'url']);

        $this->UserModel = new UserModel();

        $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 UserModel();

        $query = $builder->select('*')
                 ->limit($limit,$offset)
                 ->get();
        return $query->getResult();
   }  



}

The methods built into the CountryStateCity controller have the following functions:

  • The index() function renders the load more data template into the view.
  • The get_load_more_data() method will fetch data from database using ajax.

Step 6 – Create Views

Create home.php view file, so visit application/views/ directory and create home file. Then add the following HTML into home.php file:

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter 4 Ajax Load More on Page Scroll - LaraTutorials.com</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+"/AjaxLoadMore/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>

Create load_more_loop.php view file, so visit application/views/ directory and create load_more_loop.php file. Then add the following HTML into load_more_loop.php file:

  <?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 7 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

$routes->setDefaultController('AjaxLoadMore');
$routes->get('/', 'AjaxLoadMore::index');

Step 8 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:

http://localhost/demo/

OR

http://localhost:8080/

Conclusion

Load data while scrolling page down with jquery ajax and codeigniter 4 tutorial. In this example,you have learned how to implement load data while scrolling page down usng jquery ajax, php, mysql and bootstrap in codeigniter 4.

Recommended CodeIgniter 4 Tutorial

  1. How to Install / Download Codeigniter 4 By Manual, Composer, Git
  2. How to Remove Public and Index.php From URL in Codeigniter 4
  3. Codeigniter 4 Form Validation Example Tutorial
  4. How to add jQuery Validation on Form in Codeigniter 4 Example
  5. Codeigniter 4 Ajax Form Submit Validation Example
  6. Codeigniter 4 File Upload Validation Example
  7. Image Upload with Validation in Codeigniter 4
  8. Codeigniter 4 Image Upload Preview Using jQuery Example
  9. Codeigniter 4 Ajax Image Upload Preview Example
  10. How to Upload Multiple Images in Codeigniter 4
  11. Codeigniter 4 Multiple Image Upload with Preview
  12. Codeigniter 4 Pagination Example; Create Pagination in Codeigniter
  13. Simple Codeigniter 4 CRUD with Bootstrap and MySQL Example
  14. Codeigniter 4 CRUD with Datatables Example
  15. Codeigniter 4 Image Crop and Save using Croppie Example
  16. Codeigniter 4 Dependent Dropdown using jQuery Ajax Example
  17. CodeIgniter 4 Rest Api CRUD Example
  18. Codeigniter 4 Login Registration and Logout Example
  19. Codeigniter 4 PDF Example: Generate PDF in Codeigniter 4 using Dompdf

Be First to Comment

Leave a Reply

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