Codeigniter 4 Load More Data on Page Scroll using jQuery Ajax - Yudhy Network

Share on:

Yudhy Network - Codeigniter 4 load more data using jQuery ajax. In this tutorial, you will learn how to implement load data while scrolling page down with jquery ajax and codeigniter 4 app

Load data while scrolling page down with jQuery Ajax and Codeigniter 4 app. In this example, you will learn how to implement dynamic load more data on page scroll using jquery ajax in Codeigniter 4 with bootstrap 4.

Sometimes you need to load data list on page scrolling and without refresh the whole web page. In this Codeigniter 4 ajax load more tutorial, you will learn how to load data or data list and place data to hmtl elements.

Load data while scrolling page down with jQuery Ajax and Codeigniter 4

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Create Model File
  • Create Controller
  • Create Views
  • Test App On Browser

Step 1: Download 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 setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”

Step 2: Basic Configurations

Next, you will set 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 With 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 Credentials

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 = 'contacts';

    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.

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

Recommende CodeIgniter 4 Tutorial

Recommended:- CodeIgniter 4 jQuery Form Validation Example
Recommended:- CodeIgniter 4 Ajax Form Submit Validation Example
Recommended:- CodeIgniter 4 Image Upload With Preview Example
Recommended:- CodeIgniter 4 Pagination Example Tutorial
Recommended:- Codeigniter 4 Ajax Image Upload with Preview Example
Recommended:- Codeigniter 4 PDF Generator Tutorial Example
Recommended:- CodeIgniter 4 First Crud Example Tutorial
Recommended:- CodeIgniter 4 Rest Api Example Tutorial
Recommended:- Codeigniter 4 Login And Registration Tutorial Example
Recommended:- Send Email in CodeIgniter 4 With SMTP
Recommended:- CodeIgniter 4 Ajax Crud with datatables and Bootstrap Modals
Recommended:- Crop and Save Image using jQuery Coppie in Codeigniter 4
Recommended:- Codeigniter 4 Google Map Multiple Markers Example
Recommended:- Codeigniter 4 Dynamic Dependent Dropdown with Ajax
Recommended:- Codeigniter 4 Autocomplete Textbox From Database using Typeahead JS
Recommended:- Codeigniter 4 Get Latitude and Longitude From Address

Please ask in the comments!

Suport : Cotekno.Com

comments powered by Disqus