Load More Data on Page Scroll CodeIgniter 4 Tutorial

Reading Time: 7 minutes
4,584 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.

Here, we have some other useful articles to load more data.

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.

Learn More –

Let’s get started.


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Environment (.env) Setup

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

Either we can do via renaming file as simple as that. Also we can do by terminal command.

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.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.


Create Database Tables

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 Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string values.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = admin
database.default.password = admin
database.default.DBDriver = MySQLi
database.default.DBPrefix =
database.default.port = 3306
  

Now, database successfully connected with the 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 --suffix

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

Open project terminal and start development server via command:

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.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

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.