Ajax Load More Data On Page Scroll With JQuery Using Codeigniter 4 Tutorial


Share:
Published By: Admin, Published On: Sep 03, 2021, Category: Codeigniter 4 Codeigniter


Hello Friends,

Now let's see example of how to use ajax load more data on page scroll with jquery in codeigniter 4. This is a short guide on codeigniter 4 if ajax load more data on page scroll with jquery. Here you will learn how to use ajax load more data on page scroll with jquery in codeigniter 4. We will use how to use if ajax load more data on page scroll with jquery using codeigniter 4. Let's get started with how to ajax load more data on page scroll with jquery use in codeigniter 4.

Here i will give you many example how you can use ajax load more data on page scroll with jquery in codeigniter 4.

Step 1 : Install New Codeigniter App

we require to download or install codeigniter project, it can install in a two ways, so first fire bellow command:

<?php
composer create-project codeigniter4/appstarter
?>
Step 2 : Commission Error Handling

In codeigniter 4 you have to turn on the error handling by setting up display_errors property to 1 from 0, make sure to change the values in app/Config/Boot/development.php and app/Config/Boot/production.php files.

ini_set('display_errors', '1');
Step 3 : Create Table And Insert Data

In this is step to generate a database table in your application 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',
    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');
Step 4 : Connect To Database

Open the following file, and insert database name, username and password into the file.

Path : app/Config/Database.php

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

If you are a Mac user or anyhow getting the CodeIgniter\Database\Exceptions\DatabaseException or Unable to connect database: Codeigniter errors. Then, you can follow the given below instruction to get rid of the mentioned issues.

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

# MAMP
public $default = [
  'hostname' => '/Applications/MAMP/tmp/mysql/mysql.sock',
]
Step 5 : 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'];
}
Step 6 : 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();
   }
}
Step 7 : 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.

Path : app/Config/Routes.php

$routes->get('/', 'AjaxLoadMore::index');
Step 8 : 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>Ajax Load More Data On Page Scroll With JQuery Using Codeigniter 4 Tutorial - MyWebtuts.com</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; ?>
Step 9 : Start CI Project

Now, start the Codeigniter project, moreover execute the given url on the browser to view the app in the browser.

php spark serve

Then next run the url in your browser.

http://localhost:8080

It will help you....

Share: