Load More Data on Page Scroll CodeIgniter 4 Tutorial

Share this Article
Reading Time: 7 minutes
7 Views

Suppose we have a large data set. Loading all data at once in a datatable or in a page results page crash or application will not work. To fix this issue we have several different different solutions.

Solutions to load large data set –

Inside this article, we will see the concept of Load More Data on Page Scroll CodeIgniter 4. This article is very very easy to learn and implement in codeigniter 4 application.

We will implement the concept of data loading on page scroll in CodeIgniter 4.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed. Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Settings Environment Variables

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


Create Database & Tables To Application

We need to create a database. For database we will use MySQL. We have 2 options available to create database. Either we can use PhpMyAdmin Manual interface Or we can use command to create.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.

Next, we need to create a table inside database.

CREATE TABLE products (
     id int(5) unsigned NOT NULL AUTO_INCREMENT,
     name varchar(100) NOT NULL,
     description text,
     PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 
#--------------------------------------------------------------------
# DATABASE
#-------------------------------------------------------------------- 
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
   

Now, database successfully connected with application.


Create Data Seeder

Open project into terminal and run this spark command to create seeder file.

$ php spark make:seeder Product --suffix

It will create a file ProductSeeder.php at /app/Database/Seeds folder.

Open ProductSeeder.php and write this code into it.

<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;
use Faker\Factory;

class ProductSeeder extends Seeder
{
    public function run()
    {
        for ($i = 0; $i < 100; $i++) { 
			//to add 10 products. Change limit as desired
            $this->db->table('products')->insert($this->generateProducts());
        }
    }

    private function generateProducts(): array
    {
        $faker = Factory::create();
        return [
            'name' => $faker->name,
			'description' => $faker->sentence(6)
        ];
    }
}

Seed data into database table

Run spark command to seed data into respective table.

$ php spark db:seed ProductSeeder

Commands will seed data into products table.


Create Controller

Open project into terminal and run this spark command to create controller file.

$ php spark make:controller Site --sufix

It will create SiteController.php at /app/Controllers folder.

Open SiteController.php and write this code into it,

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class SiteController extends BaseController
{
	private $perPage = 10;

	public function __construct()
	{
		$this->db = db_connect();
	}

	public function index()
	{
		$builder = $this->db->table("products");

		$count = $builder->countAllResults();

		if (!empty($this->request->getVar("page"))) {

			$start = $this->request->getVar("page") * $this->perPage;
			$query = $builder->limit($start, $this->perPage)->get()->getResult();

			$data['products'] = $query;
			$data['count'] = $count;

			return view('ajax_product', $data); // dynamic product list
		} else {
			$query = $builder->limit($this->perPage, 0)->get()->getResult();
			$data['products'] = $query;
			$data['count'] = intval($count / $this->perPage);
			return view('products', $data);
		}
	}
}
  • private $perPage = 10; – When we scroll page, 10 rows load at a time.
  • $builder = $this->db->table(“products”); – Creating a query builder instance
  • $count = $builder->countAllResults(); – Count total products in table
  • $this->request->getVar(“page”) – Read request variable “page”
  • $query = $builder->limit($start, $this->perPage)->get()->getResult(); – Get total products on the basis of offset and limit.

Create Layout Files

Create products.php and ajax_product.php files at /app/Views folder.

When we open products list products.php file will be loaded first, while scrolling ajax request will create dynamic product list on the basis of offset and limit and uses layout ajax_product.php and appends to the products.php page.

Open products.php and write this complete code into it.

<!DOCTYPE html>
<html>

<head>
    <title>Load More Data on Page Scroll CodeIgniter 4 Tutorial</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>

    <div class="container">
        <h2 class="text-center">Load More Data on Page Scroll CodeIgniter 4 Tutorial</h2>
        <br />
        <div class="col-md-12" id="ajax-post-container">
            <?php foreach ($products as $product) { ?>
                <div>
                    <h3><a href="#"><?php echo $product->name ?></a></h3>
                    <p><?php echo $product->description ?></p>
                </div>
            <?php } ?>
        </div>
    </div>


    <script type="text/javascript">

        var page = 1;

        var total_pages = <?php print $count ?>;

        $(window).scroll(function() {
            if ($(window).scrollTop() + $(window).height() >= $("#ajax-post-container").height()) {
                page++;
                if (page < total_pages) {
                    loadMore(page);
                }
            }
        });


        function loadMore(page) {
            $.ajax({
                    url: '?page=' + page,
                    type: "GET",
                    beforeSend: function() {}
                })
                .done(function(data) {
                    $("#ajax-post-container").append(data);
                });
        }
    </script>


</body>

</html>

Open ajax_product.php and write this complete code into it.

This layout will be used to attach dynamic products when we do page scroll. This file is called inside controller.

<?php foreach($products as $product){ ?>
  
<div>
	<h3><a href="#"><?php echo $product->name ?></a></h3>
	<p><?php echo $product->description ?></p>	
</div>
  
<?php } ?>
  

Create Route

Open Routes.php from /app/Config folder. Add this route into that file.

// ...

$routes->get("products", "SiteController::index");

//...

Application Testing

Start development server:

$ php spark serve

URL: http://localhost:8080/products

We hope this article helped you to Load More Data on Page Scroll CodeIgniter 4 Tutorial in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here

Leave a Comment