• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I display a Codeigniter 3 pagination as JSON?

I am working on a blog application with Codeigniter 3.1.8.

Currently, its admin area is well separated from the frontend.

In the frontend, I have managed to replace "classic" Codeigniter views with JSONS. (The JSONS are displayed and "handled" with AngularJS):

private function _initPagination($path, $totalRows, $query_string_segment = 'page') {
        //load and configure pagination
        $config['base_url'] = base_url($path);
        $config['query_string_segment'] = $query_string_segment;
        $config['enable_query_strings'] =TRUE;
        $config['reuse_query_string'] =TRUE;
        $config['total_rows'] = $totalRows;
        $config['per_page'] = 12;
        if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
            $_GET[$config['query_string_segment']] = 1;

        $limit = $config['per_page'];
        $offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;

        return ['limit' => $limit, 'offset' => $offset];

    public function index() {

    //call initialization method
        $config = $this->_initPagination("/", $this->Posts_model->get_num_rows());

        $data = $this->Static_model->get_static_data();
        $data['pages'] = $this->Pages_model->get_pages();
        $data['categories'] = $this->Categories_model->get_categories(); 

        //use limit and offset returned by _initPaginator method
        $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);

        // All posts

What I have not been able to do (despite tormenting my brain), is display the pagination of the posts as JSON too.

My pagination view:

<div class="pagination-container text-center">
    <?php echo $this->pagination->create_links(); ?>

I have tried 

echo json_encode(['pagination' => $this->pagination->create_links()]);

It does not work. What shall I do?

I don't think this will work out.


This code as far as I know only generates HTML template. 

I had a similar issue and I have created custom library that can output it as JSON object.

To create the pagination you need the total pages count and amount of results per page.

$res['max_pages'] = ceil($totalImagesCount / MAX_RESULTS_PER_PAGE);

This is some example code I have used.

I hope I help you a bit!

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.