Dynamically Load Data on Page Scroll in CodeIgniter using jQuery and Ajax

Dynamically Load Data on Page Scroll in CodeIgniter using jQuery and Ajax

Codeignite 3 Ajax Load More – Today we would love to share with how to load data on page scroll using ajax load more. We will load data on page scrolling on web page without reload or refresh the whole web page.

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

How to Dynamically Load Data on Page Scroll in CodeIgniter using jQuery and Ajax

By using the following steps, you can load data dynamically on page scroll using jquery ajax and php in codeigniter:

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Make New Controller
  • Create Views
  • Start Development server
  • Conclusion

Download Codeigniter Project

In this step we will download the latest version of Codeigniter, Go to this link Download Codeigniter. Download the fresh setup of codeigniter and unzip the setup in your local system xampp/htdocs/ and also rename your project folder name to demo.

Basic Configurations

Next we will set the some basic configuration on config.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

$config['base_url'] = 'http://localhost/demo';

Create Database With Table

In this step, we need to create 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 IF NOT EXISTS users(
id int(10) unsigned NOT NULL AUTO_INCREMENT,
name varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16 ;

Setup Database Credentials

In this step, We need to connect our project to database. we need to go application/config/ and open database.php file in text editor. After open the file in text editor, We need to setup database credential in this file like below.

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'demo',
	'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
);

Create Controller

Now we need to create a controller name Ajax.php. In this controller we will create some method/function. We will create first function name load_list(), it will display data when the page load first time. Next function will create name get_ajax_load_more(), it will load data by calling ajax method and append the data on main div.

<?php
class Ajax extends CI_Controller {
 
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->limit = 5;
    }

   public function load_list(){
        $limit = $this->limit;
        $data['users'] = $this->get_load_more_data($limit,'');
        $this->load->view('ajax_load_more_list', $data);
    }
   public function get_ajax_load_more(){
        $limit = $this->limit; 
        $page = $limit * $this->input->get('page');
        $data['users'] = $this->get_load_more_data($limit,$page);
        $isExist = $this->load->view('load_more_loop', $data);
        if($isExist){
            echo json_encode($isExist);
        }
   } 
   function get_load_more_data($limit, $offset = ''){
        $this->db->select('name');
        $this->db->from('users');
        $this->db->limit($limit,$offset);
        $data = $this->db->get()->result();
        return $data;
   }

  
}

Create Views

Now we need to create view for load data list name ajax_load_more_list.php. After create this view put the below html in view.

<!DOCTYPE html>
<html>
<head>
  <title>Codeigniter Ajax Load More</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+"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>

Now we need to create next view name load_more_loop.php and put the below html code here.

  <?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; ?>

Start Development server

For start development server, Go to the browser and hit below the url.

http://localhost/demo/ajax/load_list

Conclusion

In this codeigniter ajax load more tutorial – We have created a form for loading data using ajax without reload the web page.

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

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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