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

11-Apr-2023

.

Admin

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

Hi guys,

Today i will explained How to Ajax Load More Data On Page Scroll With JQuery Example in Codeigniter 4. This example is so easy to use in Codeigniter 4.

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.

So let's start to the example.

Step 1 : Install New Codeigniter App


composer create-project codeigniter4/appstarter

Step 2 : 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');

Step 3 : Create Table And Insert Data

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 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',

]

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.

$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>Codeigniter 4 Ajax Load More Data On Page Scroll With JQuery Tutorial - Nicesnippets.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

Now you can check your own.

I hope it can help you...

#Codeigniter 4

#Codeigniter