PHP Codeigniter – Load more data on page scroll using jQuery and Ajax

PHP Codeigniter – Load more data on page scroll using jQuery and Ajax

In this post we will give you information about PHP Codeigniter – Load more data on page scroll using jQuery and Ajax. Hear we will give you detail about PHP Codeigniter – Load more data on page scroll using jQuery and AjaxAnd how to use it also give you demo for it if it is necessary.

In this PHP Codeigniter tutorial, I will let you know how to implement load more feature or you can say infinite scroll in Codeignite app.

In the web development, Sometime we need to show the page numbers with navigation link for pagination to load paginated records and sometime we need to load data on page scrolling without refreshing the whole page.

Infinite Scroll is the most user-friendly feature to add pagination in the data list.

Infinite scroll pagination replace the old pagination UI (conventional pagination) because when user clicks on the page number and navigate to next page then it reloads all the elements again in the page and this costs the bandwidth mainly when user browsing something in a mobile with limited data plan.

I will assume that you have downloaded fresh version of Codeigniter 3 to test this example.



Step 1: Database configuration

In the first step, I will create a new database for this example called tutorials and create new table posts in this tutorials database.

CREATE TABLE 'posts' (
 'id' int(11) NOT NULL AUTO_INCREMENT,
 'title' varchar(255) NOT NULL,
 'description' text NOT NULL,
 'created_at' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 'updated_at' timestamp NULL DEFAULT NULL,
 PRIMARY KEY ('id')
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Now I have to modify the database configuration file with updated details in the Codeigniter application.


application/config/database.php

<?php
defined('BASEPATH') ORexit('No direct script access allowed');


$active_group='default';
$query_builder=TRUE;


$db['default'] =array(
	'dsn'=>'',
	'hostname'=>'localhost',
	'username'=>'root',
	'password'=>'',
	'database'=>'tutorials',
	'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 2: Add Route

In this step, I will add one route in the route file to manage infinite scroll on data list.


application/config/routes.php

<?php
defined('BASEPATH') ORexit('No direct script access allowed');


$route['default_controller'] ='welcome';
$route['404_override'] ='';
$route['translate_uri_dashes'] =FALSE;


$route['post'] ='PostController';



Step 3: Create Controller

In this step, I will create a controller “PostController” to manage post data with index method.


application/controllers/PostController.php

<?php
defined('BASEPATH') ORexit('No direct script access allowed');

classPostControllerextends CI_Controller {


  private$perPage=10;
	
    publicfunctionindex()
    {
     $this->load->database();
     $count=$this->db->get('posts')->num_rows();


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


      $start=$this->input->get("page") *$this->perPage;
      $query=$this->db->limit($start, $this->perPage)->get("posts");
      $data['posts'] =$query->result();
      $data['count']=$count;

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

     }else{
      $query=$this->db->limit($this->perPage,)->get("posts");
      $data['posts'] =$query->result();
      $data['count']=$count;

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


}




Step 4: Create View Files

In this step, I will create here two files, first one for the normal page load view with ajax query and another for ajax page load view.


application/views/post.php

<!DOCTYPE html>
<html>
<head>
	<title>PHP Codeigniter load more data on page scroll</title>
	<linkrel="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>

<divclass="container">
	<h2class="text-center">PHP Codeigniter 3 - load more data with infinite scroll pagination</h2>
	<br/>
	<divclass="col-md-12"id="ajax-post-container">
		<?php
		  $this->load->view('ajax_post', $posts);
		?>
	</div>
</div>


<divclass="loader"style="display:none">
	<imgsrc="<?php print base_url('loader.gif')?>">
</div>


<script type="text/javascript">
	var page =1;
	var total_pages =<?php print $count?>;
 
	$(window).scroll(function() {
	    if($(window).scrollTop() + $(window).height() >= $(document).height()) {
	        page++;
	        if(page < total_pages) {
	        	loadMore(page);
	        }
	    }
	});


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


</body>
</html>



application/views/ajax_post.php

<?phpforeach($postsas$post){ ?>
<div>
	<h3><a href=""><?phpecho$post->title?></a></h3>
	<p><?phpecho$post->description?></p>	
</div>
<?php } ?>


Auto Load More Data on Page Scroll with jQuery and PHP Laravel

Label :

PHP

OOP

HTML

jQuery

Web Development

JavaScript

Codeigniter

Hope this code and post will helped you for implement PHP Codeigniter – Load more data on page scroll using jQuery and Ajax. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

33  +    =  43

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US