Sunday 26 August 2018

Codeigniter - Load More Data on page scroll using Ajax



An ideal UI / UX is required for your website if you want to standout in the current internet world. Here in every day we can see rapid changes with new stylish innovation in website design. And there are seamlessly changes in one UI like pagination has been replace with infinite page scroll. The Major social media site like Facebook or Youtube has been use this type of infinite page scroll pagination for load data on page scroll.

This type of infinite scroll pagination replace old pagination UI with page numbers with navigation link and loading paginated records with their respective pages links has been most of outdated design. Now lets see how can we make infinite scroll pagination like Facebook or Youtube in Codeigniter Framework using Ajax jQuery.

In one of our previous tutorial we have already seen an example of pagination in Codeigniter using Ajax and Jquery. Then after we have also seen load data on page scroll in PHP with Ajax also. Based on reference get from this both codees we will make Facebook style load data on page scroll with infinite scroll pagination.

Here we have use Codeigniter framework with Ajax and Jquery and make infinite scroll pagination by loading dynamic data on page scroll. For load dynamic data on page scroll, for this we have use jQuery scroll event and at that event Ajax request has been sent to Codeigniter controller method. In Codeigniter controller method it will send limit of fetching data and last offset details has been send to model method and in model method it will fetch data from mysql table and send to controller and controller method send to view file Ajax request and it will display on page scroll. This process will continously done on every page scroll and on every page scoll it will fetch and load dynamic data on page without refresh of web page.










Create Database Table



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `post`
--

CREATE TABLE `post` (
  `id` mediumint(8) UNSIGNED NOT NULL,
  `post_title` text,
  `post_description` text,
  `author` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for table `post`
--
ALTER TABLE `post`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `post`
--
ALTER TABLE `post`
  MODIFY `id` mediumint(8) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;


Scroll_pagination.php - Controller


This Scroll_pagination controller has two function like index() and fetch().

index() function has been use to load view scroll_pagination.php file in browser.

fetch() function has been called by the Ajax request on page scroll. This function has received data like last post data and how many total records has been fetch in next page scroll Ajax request and based on this data this method pass data to Scroll_pagination_model.php model and fetch data from mysql table.


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

class Scroll_pagination extends CI_Controller {

 function index()
 {
  $this->load->view('scroll_pagination');
 }

 function fetch()
 {
  $output = '';
  $this->load->model('scroll_pagination_model');
  $data = $this->scroll_pagination_model->fetch_data($this->input->post('limit'), $this->input->post('start'));
  if($data->num_rows() > 0)
  {
   foreach($data->result() as $row)
   {
    $output .= '
    <div class="post_data">
     <h3 class="text-danger">'.$row->post_title.'</h3>
     <p>'.$row->post_description.'</p>
    </div>
    ';
   }
  }
  echo $output;
 }

}


Scroll_pagination_model.php - Model


This Scroll_pagination_model model has been handles database related request and in this there one fetch_data() method. This method fetch post data from mysql database based on condition and return result of array object.


<?php
class Scroll_pagination_model extends CI_Model
{
 function fetch_data($limit, $start)
 {

  $this->db->select("*");
  $this->db->from("post");
  $this->db->order_by("id", "DESC");
  $this->db->limit($limit, $start);
  $query = $this->db->get();
  return $query;
 }
}
?>


scroll_pagination.php - View


In this tutorial we have use only one view file like scroll_pagination.php and this file has been load by index() method of Scroll_pagination controller. In this file we have use jQuery and Bootstrap library. Under this file we have make two jquery function like lazzy_loader() and load_data(). lazzy_loader() function create looks like Facebook and Youtube type data load effect on web page and in load_data() function we have send Ajax request to Controller method for fetch data from database. this load_data() function has been called on jQuery scroll event.


<!DOCTYPE html>
<html>
    <head>
        <title>Facebook Style Infinite Scroll Pagination in Codeigniter using Ajax</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <style>
        @-webkit-keyframes placeHolderShimmer {
          0% {
            background-position: -468px 0;
          }
          100% {
            background-position: 468px 0;
          }
        }

        @keyframes placeHolderShimmer {
          0% {
            background-position: -468px 0;
          }
          100% {
            background-position: 468px 0;
          }
        }

        .content-placeholder {
          display: inline-block;
          -webkit-animation-duration: 1s;
          animation-duration: 1s;
          -webkit-animation-fill-mode: forwards;
          animation-fill-mode: forwards;
          -webkit-animation-iteration-count: infinite;
          animation-iteration-count: infinite;
          -webkit-animation-name: placeHolderShimmer;
          animation-name: placeHolderShimmer;
          -webkit-animation-timing-function: linear;
          animation-timing-function: linear;
          background: #f6f7f8;
          background: -webkit-gradient(linear, left top, right top, color-stop(8%, #eeeeee), color-stop(18%, #dddddd), color-stop(33%, #eeeeee));
          background: -webkit-linear-gradient(left, #eeeeee 8%, #dddddd 18%, #eeeeee 33%);
          background: linear-gradient(to right, #eeeeee 8%, #dddddd 18%, #eeeeee 33%);
          -webkit-background-size: 800px 104px;
          background-size: 800px 104px;
          height: inherit;
          position: relative;
        }

        .post_data
        {
          padding:24px;
          border:1px solid #f9f9f9;
          border-radius: 5px;
          margin-bottom: 24px;
          box-shadow: 10px 10px 5px #eeeeee;
        }
        </style>
    </head>
    <body>
        <div class="container">
            <h2 align="center"><u>Facebook Style Infinite Scroll Pagination in Codeigniter using Ajax</u></h2>
            <br />
            <div id="load_data"></div>
            <div id="load_data_message"></div>
            <br />
            <br />
            <br />
            <br />
            <br />
            <br />
        </div>
    </body>
</html>
<script>
  $(document).ready(function(){

    var limit = 7;
    var start = 0;
    var action = 'inactive';

    function lazzy_loader(limit)
    {
      var output = '';
      for(var count=0; count<limit; count++)
      {
        output += '<div class="post_data">';
        output += '<p><span class="content-placeholder" style="width:100%; height: 30px;">&nbsp;</span></p>';
        output += '<p><span class="content-placeholder" style="width:100%; height: 100px;">&nbsp;</span></p>';
        output += '</div>';
      }
      $('#load_data_message').html(output);
    }

    lazzy_loader(limit);

    function load_data(limit, start)
    {
      $.ajax({
        url:"<?php echo base_url(); ?>scroll_pagination/fetch",
        method:"POST",
        data:{limit:limit, start:start},
        cache: false,
        success:function(data)
        {
          if(data == '')
          {
            $('#load_data_message').html('<h3>No More Result Found</h3>');
            action = 'active';
          }
          else
          {
            $('#load_data').append(data);
            $('#load_data_message').html("");
            action = 'inactive';
          }
        }
      })
    }

    if(action == 'inactive')
    {
      action = 'active';
      load_data(limit, start);
    }

    $(window).scroll(function(){
      if($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive')
      {
        lazzy_loader(limit);
        action = 'active';
        start = start + limit;
        setTimeout(function(){
          load_data(limit, start);
        }, 1000);
      }
    });

  });
</script>






8 comments:

  1. Hi sir, thanks for your article but i have a problem. i used new version of CI but the load_data got blank. where is the problem sir? can u help me? thank you.

    ReplyDelete
  2. Hello dude!. Your script rocks! but I have a problem here, the custom message of "No more results found" it is not working on my machine even when the post limit has been reached out.

    Can you explain to me why is this occurring?

    ReplyDelete
  3. how if there are search with start and limit result?

    ReplyDelete