AJAX-based Pagination like google content without reloading the entire webpage, use simple CodeIgniter pagination, and apply the following pagination code with jquery:


Following code to create database table for making ajax pagination using CodeIgniter.

Database structure:

-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Dec 28, 2020 at 02:47 AM
-- Server version: 10.4.17-MariaDB
-- PHP Version: 7.3.25

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `ci_tutorial`
--

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

--
-- Table structure for table `myposts`
--

CREATE TABLE `myposts` (
  `id` int(11) NOT NULL,
  `title` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `postdate` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `category` varchar(250) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

--
-- Dumping data for table `myposts`
--

INSERT INTO `myposts` (`id`, `title`, `postdate`, `category`) VALUES
(66, 'Using htaccess to deny access to files and directories', '22-11-2020', ''),
(68, 'PUBG Mobile India Full Game Download Android And iOS', '22-11-2020', ''),
(69, 'Bluestacks - How to play mobile games in PC', '22-11-2020', ''),
(70, 'Avada - Website Builder For WordPress and WooCommerce download as free', '22-11-2020', ''),
(71, 'Download Farming Simulator 19 For Free 2020', '23-11-2020', ''),
(72, 'How To Download Free Grand Theft Auto V For PC', '23-11-2020', ''),
(73, 'How to download WhatsApp Desktop Or PC', '23-11-2020', ''),
(74, 'Pagination in Codeigniter With Bootstrap 4', '23-11-2020', ''),
(75, 'How To Use Phone by Google Caller ID and spam protection App', '23-11-2020', ''),
(76, 'Minecraft Caves and Clifs 1.17 Android Download', '24-11-2020', ''),
(77, 'PHP Date and Time - complete tutorial for beginners', '24-11-2020', ''),
(78, 'High-speed Net - Secret Jio APN Settings', '24-11-2020', ''),
(79, 'How to upload multiple files into CodeIgniter', '25-11-2020', ''),
(80, 'How to upload multiple files with JavaScript and PHP', '25-11-2020', ''),
(81, 'Crash Bandicoot 4 Its About Time Full Game For PC Free Download', '26-11-2020', ''),
(82, '5 Easy ways to make money online and quickly', '26-11-2020', ''),
(83, 'How to Complete 4000 Hours of Watch Time on YouTube This Year As A Small Creator', '26-11-2020', ''),
(84, 'Zip And Unzip Files in Windows Pc', '26-11-2020', ''),
(85, 'How To Create And Use Google Form', '26-11-2020', ''),
(86, 'How To Create A Paytm Account With KYC', '27-11-2020', ''),
(87, 'Fixnow - Plumbing HTML Template download as free', '27-11-2020', ''),
(88, 'Tips And Tricks to increase PC performance in Windows 10', '27-11-2020', ''),
(89, 'Error 0x80070002 - Windows Update', '27-11-2020', ''),
(90, 'How to stop automatic updates on Windows 10', '28-11-2020', ''),
(91, 'How to speed up your internet speed', '28-11-2020', ''),
(92, 'How to make your Facebook profile as private', '28-11-2020', ''),
(94, 'The most effective method to Import CSV file data to MySQL in CodeIgniter', '28-11-2020', ''),
(96, 'How to create and use UPI', '01-12-2020', ''),
(97, '2 Ways to activate Windows 10 FREE without additional software', '01-12-2020', ''),
(98, 'Jio Free Data Tricks 2021', '02-12-2020', ''),
(99, 'How To Download Among Us PC For Free', '02-12-2020', ''),
(100, 'How can I find out which graphics card I have in my PC', '02-12-2020', ''),
(101, 'How to Make Money with Your Blog in 2021', '02-12-2020', ''),
(102, 'How to Format USB Flash Drive Using CMD', '02-12-2020', ''),
(103, 'Troubleshoot problems updating Windows 10', '02-12-2020', ''),
(104, 'How to Create a Bootable Pendrive using cmd', '02-12-2020', ''),
(105, '15 best Android games on playstore', '03-12-2020', ''),
(107, 'OnePlus 8T buyers guide - Everything you need to know', '03-12-2020', ''),
(108, 'PUBG Mobile India Version Latest Update- APK Download LinksAvailable on Official Website', '03-12-2020', ''),
(109, '7 Ways to Improve Your Computer Performance', '03-12-2020', ''),
(110, 'Top 5 Product Review Website Rating Blog HTML5 Templates', '03-12-2020', ''),
(111, 'Top 5 best Android emulators for PC and Mac of 2021', '04-12-2020', ''),
(112, 'The best Android phones - January 2021', '04-12-2020', ''),
(114, 'Cybersecurity Insights Report On 5G release', '14-12-2020', ''),
(115, 'GOOGLE adds a list of new partners with BeyondCorp Alliance', '14-12-2020', ''),
(116, 'PUBG Mobile India Download Now Available Beta APK', '14-12-2020', ''),
(117, 'Very high resolution images free download', '14-12-2020', ''),
(118, 'What is Creative Commons', '15-12-2020', ''),
(119, 'What is a public domain', '15-12-2020', ''),
(120, 'What is royalty free', '15-12-2020', ''),
(121, '15 best Chromebook games from Google Play', '15-12-2020', ''),
(122, 'Organizations may fail to train their employees against Cybersecurity Threats', '16-12-2020', ''),
(123, 'One Identity Highlights Barriers to Adoption of Zero Trust Framework', '17-12-2020', ''),
(125, '5 YouTube tricks to help you raise revenue 50 percentage faster Instantly', '17-12-2020', ''),
(126, 'PUBG Mobile 2 global version beta update APK OBB download', '19-12-2020', ''),
(127, 'The 15 best Android apps available now', '19-12-2020', ''),
(128, 'Can not send or receive messages on your Android phone', '19-12-2020', ''),
(129, 'Full Galaxy S21 Ultra specs leak no in-box charger allegedly confirmed', '19-12-2020', ''),
(130, 'Google Camera Go now brings HDR to budget smartphones Updated', '19-12-2020', ''),
(131, 'Sony returns all Cyberpunk 2077 order renewals: Xbox and refunds for all', '19-12-2020', ''),
(132, 'How To Calculate CPC and CTR-Formulas', '20-12-2020', ''),
(133, 'How to move the mouse cursor with the keyboard in Windows', '20-12-2020', ''),
(135, 'Top 10 Indian Information Technology Companies', '21-12-2020', ''),
(136, 'Top Indian Information Technology Companies', '21-12-2020', ''),
(137, 'TOP MOST EXPENSIVE MOBILE PHONES IN THE WORD', '21-12-2020', ''),
(138, 'Best budget gaming headphones', '21-12-2020', ''),
(139, '10 WordPress Tips to Make Your Website Secure', '21-12-2020', ''),
(140, 'IPhone12 features How Apples snappy new magnet feature works', '21-12-2020', ''),
(141, 'How to Not Get Locked Out With Two-Factor Authentication', '21-12-2020', ''),
(142, '10 best reminder apps for Android', '21-12-2020', ''),
(143, 'BEST STORY-DRIVEN GAMES ON MOBILE', '23-12-2020', 'Mobile Games'),
(144, 'Best top 5 Smart TVs in India', '23-12-2020', ''),
(145, 'SEO-friendly URLs', '24-12-2020', 'SEO Tutorial'),
(146, 'What is Canonical Tag Or link SEO', '24-12-2020', 'SEO Tutorial'),
(147, 'How to Increase Website Traffic Tips and Tricks', '26-12-2020', 'SEO Tutorial');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `myposts`
--
ALTER TABLE `myposts`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=149;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

controllers/Posts.php

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

class Posts extends CI_Controller {
    
    function __construct() {
        parent::__construct();
        $this->load->model('post');
        $this->load->library('Ajax_pagination');
        $this->perPage = 10;
    }
    
    public function index(){
        $data = array();
        
        //total rows count
        $totalrRow = count($this->post->getRows());
        
        //pagination configuration
        $config = array(
            "target" => '#postList',
            "base_url" => base_url().'posts/ajaxData',
            "total_rows" =>  $totalrRow,
            "per_page" =>  $this->perPage,
            "link_func" => 'searchFilter'
        );
       
        $this->ajax_pagination->initialize($config);
        
        //get the posts data
        $data['posts'] = $this->post->getRows(array('limit'=>$this->perPage));
        
        //load the view
        $this->load->view('posts/index', $data);
    }
    
    function ajaxData(){
        $conditions = array();
        
        //calc offset number
        $page = $this->input->post('page');
        if(!$page){
            $offset = 0;
        }else{
            $offset = $page;
        }
        
        //set conditions for search
        $keywords = $this->input->post('keywords');
        $sortBy = $this->input->post('sortBy');
        if(!empty($keywords)){
            $conditions['search']['keywords'] = $keywords;
        }
        if(!empty($sortBy)){
            $conditions['search']['sortBy'] = $sortBy;
        }
        
        //total rows count
        $totalRec = count($this->post->getRows($conditions));
        
        //pagination configuration
        $config['target']      = '#postList';
        $config['base_url']    = base_url().'posts/ajaxData';
        $config['total_rows']  = $totalRec;
        $config['per_page']    = $this->perPage;
        $config['link_func']   = 'searchFilter';
        $this->ajax_pagination->initialize($config);
        
        //set start and limit
        $conditions['start'] = $offset;
        $conditions['limit'] = $this->perPage;
        
        //get posts data
        $data['posts'] = $this->post->getRows($conditions);
        
        //load the view
        $this->load->view('posts/ajax-pagination-data', $data, false);
    }
}
?>

Models/Post.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Post extends CI_Model{
    /*
     * get rows from the posts table
     */
    function getRows($params = array()){
        $this->db->select('*');
        $this->db->from('myposts');
        //filter data by searched keywords
        if(!empty($params['search']['keywords'])){
            $this->db->like('title',$params['search']['keywords']);
        }
        //sort data by ascending or desceding order
        if(!empty($params['search']['sortBy'])){
            $this->db->order_by('title',$params['search']['sortBy']);
        }else{
            $this->db->order_by('id','desc');
        }
        //set start and limit
        if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
            $this->db->limit($params['limit'],$params['start']);
        }elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){
            $this->db->limit($params['limit']);
        }
        //get records
        $query = $this->db->get();
        //return fetched data
        return ($query->num_rows() > 0)?$query->result_array():FALSE;
    }

}
?>

libraries/Ajax_pagination.php

<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Pagination Class
 *
 * @package   CodeIgniter
 * @link      http://codeigniter.com/user_guide/libraries/pagination.html
 * 
 * @Ajax pagination functionality has added with this library. 
 * @It will helps to integrate Ajax pagination with loading image in CodeIgniter application.
 * @TutorialLink https://rathorji.in/p/ajax_pagination_like_google_using_codeigniter
 */
class Ajax_pagination{

    var $base_url        = ''; // The page we are linking to
    var $total_rows      = ''; // Total number of items (database results)
    var $per_page        = 10; // Max number of items you want shown per page
    var $num_links       =  2; // Number of "digit" links to show before/after the currently viewed page
    var $cur_page        =  0; // The current page being viewed
    var $first_link      = 'First';
    var $next_link       = '&#187;';
    var $prev_link       = '&#171;';
    var $last_link       = 'Last';
    var $uri_segment     = 3;
    var $full_tag_open   = '<div class="pagination">';
    var $full_tag_close  = '</div>';
    var $first_tag_open  = '';
    var $first_tag_close = '&nbsp;';
    var $last_tag_open   = '&nbsp;';
    var $last_tag_close  = '';
    var $cur_tag_open    = '&nbsp;<b>';
    var $cur_tag_close   = '</b>';
    var $next_tag_open   = '&nbsp;';
    var $next_tag_close  = '&nbsp;';
    var $prev_tag_open   = '&nbsp;';
    var $prev_tag_close  = '';
    var $num_tag_open    = '&nbsp;';
    var $num_tag_close   = '';
    var $target          = '';
    var $anchor_class    = '';
    var $show_count      = true;
    var $link_func       = 'getData';
    var $loading         = '.loading';

    /**
     * Constructor
     * @access    public
     * @param    array    initialization parameters
     */
    function CI_Pagination($params = array()){
        if (count($params) > 0){
            $this->initialize($params);        
        }
        log_message('debug', "Pagination Class Initialized");
    }

    /**
     * Initialize Preferences
     * @access    public
     * @param    array    initialization parameters
     * @return    void
     */
    function initialize($params = array()){
        if (count($params) > 0){
            foreach ($params as $key => $val){
                if (isset($this->$key)){
                    $this->$key = $val;
                }
            }        
        }

        // Apply class tag using anchor_class variable, if set.
        if ($this->anchor_class != ''){
            $this->anchor_class = 'class="' . $this->anchor_class . '" ';
        }
    }

    /**
     * Generate the pagination links
     * @access    public
     * @return    string
     */    
    function create_links(){
        // If our item count or per-page total is zero there is no need to continue.
        if ($this->total_rows == 0 OR $this->per_page == 0){
           return '';
        }

        // Calculate the total number of pages
        $num_pages = ceil($this->total_rows / $this->per_page);

        // Is there only one page? Hm... nothing more to do here then.
        if ($num_pages == 1){
            $info = 'Showing : ' . $this->total_rows;
            return $info;
        }

        // Determine the current page number.        
        $CI =& get_instance();    
        if ($CI->uri->segment($this->uri_segment) != 0){
            $this->cur_page = $CI->uri->segment($this->uri_segment);   
            // Prep the current page - no funny business!
            $this->cur_page = (int) $this->cur_page;
        }

        $this->num_links = (int)$this->num_links;
        if ($this->num_links < 1){
            show_error('Your number of links must be a positive number.');
        }

        if ( ! is_numeric($this->cur_page)){
            $this->cur_page = 0;
        }

        // Is the page number beyond the result range?
        // If so we show the last page
        if ($this->cur_page > $this->total_rows){
            $this->cur_page = ($num_pages - 1) * $this->per_page;
        }

        $uri_page_number = $this->cur_page;
        $this->cur_page = floor(($this->cur_page/$this->per_page) + 1);

        // Calculate the start and end numbers. These determine
        // which number to start and end the digit links with
        $start = (($this->cur_page - $this->num_links) > 0) ? $this->cur_page - ($this->num_links - 1) : 1;
        $end   = (($this->cur_page + $this->num_links) < $num_pages) ? $this->cur_page + $this->num_links : $num_pages;

        // Add a trailing slash to the base URL if needed
        $this->base_url = rtrim($this->base_url, '/') .'/';

        // And here we go...
        $output = '';

        // SHOWING LINKS
        if ($this->show_count){
            $curr_offset = $CI->uri->segment($this->uri_segment);
            $info = 'Showing ' . ( $curr_offset + 1 ) . ' to ' ;

            if( ( $curr_offset + $this->per_page ) < ( $this->total_rows -1 ) )
            $info .= $curr_offset + $this->per_page;
            else
            $info .= $this->total_rows;

            $info .= ' of ' . $this->total_rows . ' | ';
            $output .= $info;
        }

        // Render the "First" link
        if  ($this->cur_page > $this->num_links){
            $output .= $this->first_tag_open 
                    . $this->getAJAXlink( '' , $this->first_link)
                    . $this->first_tag_close;
        }

        // Render the "previous" link
        if  ($this->cur_page != 1){
            $i = $uri_page_number - $this->per_page;
            if ($i == 0) $i = '';
            $output .= $this->prev_tag_open 
                    . $this->getAJAXlink( $i, $this->prev_link )
                    . $this->prev_tag_close;
        }

        // Write the digit links
        for ($loop = $start -1; $loop <= $end; $loop++){
            $i = ($loop * $this->per_page) - $this->per_page;    
            if ($i >= 0){
                if ($this->cur_page == $loop){
                    $output .= $this->cur_tag_open.$loop.$this->cur_tag_close; // Current page
                }else{
                    $n = ($i == 0) ? '' : $i;
                    $output .= $this->num_tag_open
                        . $this->getAJAXlink( $n, $loop )
                        . $this->num_tag_close;
                }
            }
        }

        // Render the "next" link
        if ($this->cur_page < $num_pages){
            $output .= $this->next_tag_open 
                . $this->getAJAXlink( $this->cur_page * $this->per_page , $this->next_link )
                . $this->next_tag_close;
        }

        // Render the "Last" link
        if (($this->cur_page + $this->num_links) < $num_pages){
            $i = (($num_pages * $this->per_page) - $this->per_page);
            $output .= $this->last_tag_open . $this->getAJAXlink( $i, $this->last_link ) . $this->last_tag_close;
        }

        // Kill double slashes.  Note: Sometimes we can end up with a double slash
        // in the penultimate link so we'll kill all double slashes.
        $output = preg_replace("#([^:])//+#", "\\1/", $output);

        // Add the wrapper HTML if exists
        $output = $this->full_tag_open.$output.$this->full_tag_close;
        ?>
        <script>
        function getData(page){  
            $.ajax({
                method: "POST",
                url: "<?php echo $this->base_url; ?>"+page,
                data: { page: page },
                beforeSend: function(){
                    $('<?php echo $this->loading; ?>').show();
                },
                success: function(data){
                    $('<?php echo $this->loading; ?>').hide();
                    $('<?php echo $this->target; ?>').html(data);
                }
            });
        }
        </script>
        <?php
        return $output;
    }

    function getAJAXlink($count, $text) {
        $pageCount = $count?$count:0;
        return '<a href="javascript:void(0);"' . $this->anchor_class . ' onclick="'.$this->link_func.'('.$pageCount.')">'. $text .'</a>';
    }
}
// END Pagination Class
?>

views/posts/ajax-pagination-data.php

<?php if(!empty($posts)): foreach($posts as $post): ?>
    <div class="list-item"><a href="javascript:void(0);"><h5><?php echo $post['title']; ?></h5></a></div>
<?php endforeach; else: ?>
<p>Post(s) not available.</p>
<?php endif; ?>
<?php echo $this->ajax_pagination->create_links(); ?>

views/posts/index.php

<!DOCTYPE html>
<html lang="en">  
    <head>
        <title>AAjax Pagination Like Google Using CodeIgniter</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/1.11.3/jquery.min.js"></script>
        <style>
            .loading{
                position: fixed;
                left: 0px;
                top: 0px;
                width: 100%;
                height: 100%;
                z-index: 9999;
                background: url(<?php echo base_url() . 'assets/images/loading.gif'; ?>) 
                    50% 50% no-repeat rgb(249,249,249);
            }
        </style>
        <script>
            function searchFilter(page_num) {
                page_num = page_num ? page_num : 0;
                var keywords = $('#keywords').val();
                var sortBy = $('#sortBy').val();
                $.ajax({
                    type: 'POST',
                    url: '<?php echo base_url(); ?>posts/ajaxData/' + page_num,
                    data: 'page=' + page_num + '&keywords=' + keywords + '&sortBy=' + sortBy,
                    beforeSend: function() {
                        $('.loading').show();
                    },
                    success: function(html) {
                        $('#postList').html(html);
                        $('.loading').hide();
                    }
                });
            }
        </script>
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <h3>Ajax Pagination Like Google Using CodeIgniter</h3>
                  
                        <div class="post-search-panel">
                            <input type="text" id="keywords" placeholder="Search.." onkeyup="searchFilter()"/>
                            <select id="sortBy" onchange="searchFilter()">
                                <option value="">Sort By</option>
                                <option value="asc">Ascending</option>
                                <option value="desc">Descending</option>
                            </select>
                        </div>
                        <div class="post-list" id="postList">
                            <?php if (!empty($posts)): foreach ($posts as $post): ?>
                                    <div class="list-item"><a href="javascript:void(0);"><h5><?php echo $post['title']; ?></h5></a></div>
                                    <?php endforeach; ?>

                            <?php else: ?>
                                <p>Post(s) not available.</p>
                            <?php endif; ?>
                            <?php echo $this->ajax_pagination->create_links(); ?>
                        </div>
                        <div class="loading" style="display: none;"></div>
                </div>
            </div>
        </div>
    </body>
</html>

Output:


Download source code

Are you facing problems in understanding this article? download source code now