Codeigniter Ajax Infinite Scroll Pagination Example

By Hardik Savani November 5, 2023 Category : Codeigniter

In this example, we are going to lean how to implement infinite scroll example in our codeigniter application.

Infinite Scroll is amazing feature if you have news latter page, posts page or any listing page that way we don't require to load more records at time and not need to load page every time. we sometimes require to use infinite scroll in our project or application. So in this post we learn how to make infinite scroll example from scratch.

I also provide demo for infinite scroll example, so you can see there. In this example we will create "posts" table and you have to add some manually dummy data. After successfully run this example you can see layout as like bellow:

Preview:

Step 1: Download Fresh Codeigniter 3

In First step we will download fresh version of Codeigniter 3, so if you haven't download yet then download from here : Download Codeigniter 3.

Step 2: Create Database and Configuration

In this step we will create new database "test" and add new table "posts" in test database. You can use following SQL Query for create "posts" table. So let's create using bellow sql query:

item table:

CREATE TABLE IF NOT EXISTS `posts` (

`id` int(10) unsigned NOT NULL AUTO_INCREMENT,

`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,

`description` text COLLATE utf8_unicode_ci NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16 ;

After create database and table successfully, we have to configuration of database in our Codeigniter 3 application, so open database.php file and add your database name, username and password.

application/config/database.php

<?php

defined('BASEPATH') OR exit('No direct script access allowed');


$active_group = 'default';

$query_builder = TRUE;


$db['default'] = array(

'dsn' => '',

'hostname' => 'localhost',

'username' => 'root',

'password' => 'root',

'database' => 'test',

'dbdriver' => 'mysqli',

'dbprefix' => '',

'pconnect' => FALSE,

'db_debug' => (ENVIRONMENT !== 'production'),

'cache_on' => FALSE,

'cachedir' => '',

'char_set' => 'utf8',

'dbcollat' => 'utf8_general_ci',

'swap_pre' => '',

'encrypt' => FALSE,

'compress' => FALSE,

'stricton' => FALSE,

'failover' => array(),

'save_queries' => TRUE

);

Step 3: Add Route

In this step you have to add one route in our route file. We will manage infinite scroll example on single route using jquery, so let's put route as bellow code:

application/config/routes.php

<?php

defined('BASEPATH') OR exit('No direct script access allowed');


$route['default_controller'] = 'welcome';

$route['404_override'] = '';

$route['translate_uri_dashes'] = FALSE;


$route['my-post'] = 'AjaxController';

Step 4: Create Controller

Ok, now first we have to create one new controller AjaxController with index method. so create AjaxController.php file in this path application/controllers/AjaxController.php and put bellow code in this file:

application/controllers/AjaxController.php

<?php

defined('BASEPATH') OR exit('No direct script access allowed');


class AjaxController extends CI_Controller {


private $perPage = 5;


/**

* Get All Data from this method.

*

* @return Response

*/

public function index()

{

$this->load->database();

$count = $this->db->get('posts')->num_rows();


if(!empty($this->input->get("page"))){


$start = ceil($this->input->get("page") * $this->perPage);

$query = $this->db->limit($start, $this->perPage)->get("posts");

$data['posts'] = $query->result();


$result = $this->load->view('data', $data);

echo json_encode($result);


}else{

$query = $this->db->limit(5, $this->perPage)->get("posts");

$data['posts'] = $query->result();


$this->load->view('myPost', $data);

}

}


}

Step 5: Create View Files

In this step, we will create two view files as listed bellow:

myPost.php: In this file, we will display layout with infinite ajax jquery.

data.php: In this file, we manage posts table data foreach, so we have to just manage posts data here.

application/views/myPost.php

<!DOCTYPE html>

<html>

<head>

<title>Codeigniter infinite scroll pagination</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

<style type="text/css">

.ajax-load{

background: #e1e1e1;

padding: 10px 0px;

width: 100%;

}

</style>

</head>

<body>


<div class="container">

<h2 class="text-center">Codeigniter infinite scroll pagination</h2>

<br/>

<div class="col-md-12" id="post-data">

<?php

$this->load->view('data', $posts);

?>

</div>

</div>


<div class="ajax-load text-center" style="display:none">

<p><img src="http://demo.itsolutionstuff.com/plugin/loader.gif">Loading More post</p>

</div>


<script type="text/javascript">

var page = 1;

$(window).scroll(function() {

if($(window).scrollTop() + $(window).height() >= $(document).height()) {

page++;

loadMoreData(page);

}

});


function loadMoreData(page){

$.ajax(

{

url: '?page=' + page,

type: "get",

beforeSend: function()

{

$('.ajax-load').show();

}

})

.done(function(data)

{

if(data == " "){

$('.ajax-load').html("No more records found");

return;

}

$('.ajax-load').hide();

$("#post-data").append(data);

})

.fail(function(jqXHR, ajaxOptions, thrownError)

{

alert('server not responding...');

});

}

</script>


</body>

</html>

application/views/data.php

<?php foreach($posts as $post){ ?>

<div>

<h3><a href=""><?php echo $post->title ?></a></h3>

<p><?php echo $post->description ?></p>

<div class="text-right">

<button class="btn btn-success">Read More</button>

</div>

<hr style="margin-top:5px;">

</div>

<?php } ?>

Ok, now we are ready to run our Infinite Scroll example. Make sure you have some dummy records on posts table. So let's run bellow command on your root directory for quick run:

php -S localhost:8000

Now you can open bellow URL on your browser:

http://localhost:8000/my-post

Tags :
Shares