Implementing AJAX Pagination with Search in CodeIgnier

ajax-pagination-with-search-in-codeigniter

In this tutorial, you will learn how to program an Ajax pagination with search functionality. We will not be using any 3rd party libraries for PHP or JavaScript to accomplish this task so that I may pass along the highest level of programming education and insight on this topic to you.

You can just copy the code below and customize the database fields to meet your requirements. I have also provided a brief documentation within the codes so that the steps are clear.

Step 1

In your application/view, create a new folder and name it “blog”. Then inside the blog folder, create a new file and name it “index.php”. Open index.php, add the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<script type = "text/javascript" src = "//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>

<article class="navbar-form navbar-left">
    <div class="form-group">
        <input type="text" class="form-control blog_search_text" placeholder="Enter a keyword">
    </div>
    <input type = "submit" value = "Search" class = "btn btn-primary blog_search_submit" />
</article>

<br />

<div class="col-md-12 content">
    <script type="text/javascript">
    jQuery(document).ready(function($) {

        function cvf_load_all_posts(page){
            // Start the transition
            $(".cvf_pag_loading").fadeIn().css('background','#ccc');
           
            // Data to receive from our controller
            var data = {
                page: page,
                search: $('.blog_search_text').val()
            };
           
            // Send the data
            $.post("<?php echo base_url('blog/index_display')?>", data, function(response) {
                // If successful Append the data into our html container
                $(".cvf_universal_container").html(response);
                // End the transition
                $(".cvf_pag_loading").css({'background':'none', 'transition':'all 1s ease-out'});
            });
        }
       
        // Load page 1 as the default
        cvf_load_all_posts(1);
       
        // Handle the clicks
        $('body').on('click', '.cvf_universal_container .cvf-universal-pagination li.active', function(){
            var page = $(this).attr('p');
            cvf_load_all_posts(page);
           
        });
       
        // Search
        $('body').on('click', '.blog_search_submit', function(){
            cvf_load_all_posts(1);
        });
                   
    });
    </script>
       
    <div class = "cvf_pag_loading">
        <div class = "cvf_universal_container">
            <div class="cvf-universal-content"></div>
        </div>
    </div>
</div>

In the above code, we created a script that will send a request post to the controller file “http://yourwebsite.com/blog/index_display”. Our request post contains the page number we want to be loaded and the value of the search input field. We then output the response of our controller to the div container with a class name: “cvf_universal_container”.

Step 2

In you application/controller, create a new file and name it “blog.php”, inside blog.php, add the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
<?php
class Blog extends CI_Controller {

    public function __construct() {
       
        parent::__construct();
       
    }

    public function index() {
       
        $data['post_title'] = 'Blog';
       
        $this->load->view('templates/header', $data);
        $this->load->view('pages/blog/index');
        $this->load->view('templates/footer');
       
    }
   
    public function index_display() {
       
        // $this->output->enable_profiler(TRUE);
       
        // Set default variables
        $msg = '';
       
        if($this->input->post('page')){
           
            $pag_container = '';
            $where = '';
           
            // Sanitize the received page  
            $page = $this->input->post('page');
            $cur_page = $page; 
            $page -= 1;
            // Set the number of results to display
            $per_page = 5;
            $previous_btn = true;
            $next_btn = true;
            $first_btn = true;
            $last_btn = true;
            $start = $page * $per_page;
           
            if(!empty($this->input->post('search'))){
                $where = ' AND (post_title LIKE "%%' . $this->input->post('search') . '%%" OR post_content LIKE "%%' . $this->input->post('search') . '%%") ';
            }
           
            // Set the table where we will be querying data
            $table_name = "ci_posts";
           
            // Query the necessary posts
            $all_blog_posts = $this->db->query("
                SELECT * FROM "
. $table_name . "
                WHERE post_type = 'post' AND post_status = 'publish'"
.$where."
                ORDER BY post_date DESC
                LIMIT ?, ?"
, array($start, $per_page) );
           
            // At the same time, count the number of queried posts
            $blogs_count = $this->db->query("
                SELECT COUNT(ID) as blog_count FROM "
. $table_name . "
                WHERE post_type = 'post' AND post_status = 'publish'"
);
           
            // Loop into all the posts
            foreach($all_blog_posts->result() as $key => $post):
               
                // Set the desired output into a variable
                $msg .= '
                <div class = "col-md-12">      
                    <h2><a href="'
. base_url('blog/' . $post->post_name) . '">' . $post->post_title . '</a></h2>
                    <p>'
. $post->post_excerpt . '</p>
                </div>'
;
               
            endforeach;
           
            // Optional, wrap the output into a container
            $msg = "<div class='cvf-universal-content'>" . $msg . "</div><br class = 'clear' />";
                   
            // This is where the magic happens
            $count = $blogs_count->row();
            $no_of_paginations = ceil($count->blog_count / $per_page);

            if ($cur_page >= 7) {
                $start_loop = $cur_page - 3;
                if ($no_of_paginations > $cur_page + 3)
                    $end_loop = $cur_page + 3;
                else if ($cur_page <= $no_of_paginations && $cur_page > $no_of_paginations - 6) {
                    $start_loop = $no_of_paginations - 6;
                    $end_loop = $no_of_paginations;
                } else {
                    $end_loop = $no_of_paginations;
                }
            } else {
                $start_loop = 1;
                if ($no_of_paginations > 7)
                    $end_loop = 7;
                else
                    $end_loop = $no_of_paginations;
            }
           
            // Pagination Buttons logic        
            $pag_container .= "
            <div class='cvf-universal-pagination'>
                <ul>"
;

            if ($first_btn && $cur_page > 1) {
                $pag_container .= "<li p='1' class='active'>First</li>";
            } else if ($first_btn) {
                $pag_container .= "<li p='1' class='inactive'>First</li>";
            }

            if ($previous_btn && $cur_page > 1) {
                $pre = $cur_page - 1;
                $pag_container .= "<li p='$pre' class='active'>Previous</li>";
            } else if ($previous_btn) {
                $pag_container .= "<li class='inactive'>Previous</li>";
            }
            for ($i = $start_loop; $i <= $end_loop; $i++) {

                if ($cur_page == $i)
                    $pag_container .= "<li p='$i' class = 'selected' >{$i}</li>";
                else
                    $pag_container .= "<li p='$i' class='active'>{$i}</li>";
            }
           
            if ($next_btn && $cur_page < $no_of_paginations) {
                $nex = $cur_page + 1;
                $pag_container .= "<li p='$nex' class='active'>Next</li>";
            } else if ($next_btn) {
                $pag_container .= "<li class='inactive'>Next</li>";
            }

            if ($last_btn && $cur_page < $no_of_paginations) {
                $pag_container .= "<li p='$no_of_paginations' class='active'>Last</li>";
            } else if ($last_btn) {
                $pag_container .= "<li p='$no_of_paginations' class='inactive'>Last</li>";
            }

            $pag_container = $pag_container . "
                </ul>
            </div>"
;
           
            // We echo the final output
            echo
            '<div class = "cvf-pagination-content">' . $msg . '</div>' .
            '<div class = "cvf-pagination-nav">' . $pag_container . '</div>';
           
        }  
   
    }

    public function view($post_name) {
   
       
        $data['blog'] = $this->post_model->get_post(array('post_name' => $post_name));

        if (!empty($data['blog'])) {
           
            $data['post_title'] = $data['blog']->post_title;
           
            $this->load->view('templates/header', $data);
            $this->load->view('pages/blog/view', $data);
            $this->load->view('templates/footer');
           
        } else {
            show_404();
        }
   
       
    }
}

Step 3

In your application/view, create another file and name it “view.php”, open view.php and add the following code:

1
2
<h1><?php echo $blog->post_title; ?></h1>
<p><?php echo autop($blog->post_content); ?></p>

The above code will display the contents of the clicked post.

Styling

If you need a quick styling for your pagination, you can add the following code into your css file:

1
2
3
4
5
6
.cvf_pag_loading {padding: 20px;}
.cvf-universal-pagination ul {margin: 0; padding: 0;}
.cvf-universal-pagination ul li {display: inline; margin: 3px; padding: 4px 8px; background: #FFF; color: black; }
.cvf-universal-pagination ul li.active:hover {cursor: pointer; background: #1E8CBE; color: white; }
.cvf-universal-pagination ul li.inactive {background: #7E7E7E;}
.cvf-universal-pagination ul li.selected {background: #1E8CBE; color: white;}

Now taste the AJAXified pagiantion in action. We have done a great job already.
If you have enjoyed this tutorial please do share with others. You know, sharing means caring :).



Do you need help with a project? or have a new project in mind that you need help with?

Contact Me