2

How to make pagination with this ajax, json format in codeigniter? I made a pagination without ajax and it's working. But I am working now on ajax and json format now in loading my data. I don't have idea on how to add the pagination. Is there anyone who can help me?

Here's my full code.

Thankyou

Model:

public function getManufacturerRecords(){ //retrieve data
    $query = $this->db->get('manufacturer');
    return $query->result();
}

Controller

public function index(){
    if($this->session->userdata('is_logged_in')){
        $this->load->view('../template/header');
        $this->load->view('manufacturer');
        $this->load->view('../template/footer');
    } else {
        redirect('main/restricted');
    }
}

public function manufacturer_list(){
    $result = $this->manufacturer_model->getManufacturerRecord();
    echo json_encode($result);
}

View:

<table class="table table-condensed table-bordered table-striped" style="width:50%">
    <thead>
       <tr>
           <th>ID</th>
           <th>Manufacturer</th>
           <th>Actions</th>
       </tr>
    </thead>
    <tbody id="showdata">

    </tbody>
</table>

Ajax:

showRecords();
function showRecords(){
   $.ajax({
       url: "<?=base_url()?>manufacturer/manufacturer_list",
       type: 'POST',
       dataType: 'json',
       success: function(data){
           var html = '';
           for(i=0; i<data.length; i++){
               html += '<tr align="center">'+
                          '<td>'+data[i].id+'</td>'+
                          '<td>'+data[i].brand+'</td>'+
                          '<td>'+'<button class="btn btn-primary edit-data" data="'+data[i].id+'">Edit</button>'+ '&nbsp;'+
                          '<button class="btn btn-danger delete-data" data="'+data[i].id+'">Delete</button>'+'</td>'+
                       '</tr>';
           }
           $("#showdata").html(html);
       },
       error: function(){
           alert('Could not load the data');
       }
    });
}
  • You can modified your pagination please check this. http://stackoverflow.com/questions/31553329/how-to-load-view-more-comments-using-ajax-and-codeigniter/31554418#31554418 However I will suggest you data-table js library as you have table in your view http://stackoverflow.com/questions/42697776/codeigniter-how-to-fetch-datatable-data-from-ajax/42732388#42732388 Please let me know if any confusion – shafiq.rst Mar 25 '17 at 04:02
  • The loadmore function is not pagination right? It just like if u click the button it will load more data? – Genina Anne Gabuten Mar 25 '17 at 06:31
  • Have you made a pagination with data load ajax? @shafiq – Genina Anne Gabuten Mar 25 '17 at 06:40
  • Yes I did. Through load more you can make Ajax pagination. I will share code with u. However I suggest to check datatable. It has inbuilt Ajax pagination. Check second link in my comment – shafiq.rst Mar 25 '17 at 08:50
  • Can you help me with this sir? yea I know that it has built in pagination but I don't know how to implement on my ajax code sadly. – Genina Anne Gabuten Mar 25 '17 at 09:07
  • Now it says,. No data available in table – Genina Anne Gabuten Mar 25 '17 at 09:57
  • @shafiq what does "draw" => $this->input->get('draw'), do? – Genina Anne Gabuten Mar 25 '17 at 10:01
  • Please check my answer. Let me know if any issue. Don't worry about the draw. It is sent by dataTable js to controller for handling pagination. – shafiq.rst Mar 25 '17 at 16:40

2 Answers2

2

1.Codeigniter pagination with ajax

Controller

/** Load pagination library **/
$this->load->library('pagination');
/** initialize the config **/
$config['per_page'] = 20; /** per page records **/
$config['uri_segment'] = 3; /** in case your url has different please use proper uri segment**/
$config['cur_page'] = $this->uri->segment(3) ? $this->uri->segment(3): '1';
$config['full_tag_open'] = '<ul class="pagination">'; /** we will use this class for ajax call or you can customize pagination as you want**/
$config['full_tag_close'] = '</ul>';
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = '<li class="active"><a>';
$config['cur_tag_close'] = '</a></li>';
$config['next_tag_open'] = '<li class="next">';
$config['next_tag_close'] = '</li>';
$config['prev_tag_open'] = '<li class="prev">';
$config['prev_tag_close'] = '</li>';

$offset = $this->uri->segment(3);
if ($offset == 1 || $offset == '' || !intval($offset)) 
    $offset = 0;
$offset ? $offset : 0;
$limit = $config['per_page'];
$q = "SELECT * FROM TABLE NAME "; /** change your query or use model **/
$query = $this->db->query($q);
$config['total_rows'] = $query->num_rows();/** COUNT OF TOTAL RECORDS IN DATABASE **/;
/** get your data **/
$q .= " LIMIT $offset, $limit";
$query = $this->db->query($q);
$data['data'] = $query->result();
$config['base_url'] = 'SITE_NAME/CONTROLLER_NAME/METHOD_NAME';
$this->pagination->initialize($config);
$data['links'] = $this->pagination->create_links(); /** this will create  pagination  links **/
$data['ajax'] = false;
if ($this->input->is_ajax_request()) {
    /*** return only Table view if its ajax call **/
    $data['ajax'] = true;
    echo json_encode($this->load->view('manufacturer',$data,true));
}else{
    $this->load->view('../template/header');
    $this->load->view('manufacturer',$data);
    $this->load->view('../template/footer');
}

view manufacturer

<?php if(!$ajax){?>
    <div class="loadData">
}?>
<table  id="showdata" class="table table-condensed table-bordered table-striped" style="width:50%">
    <thead>
       <tr>
           <th>ID</th>
           <th>Manufacturer</th>
           <th>Actions</th>
       </tr>
    </thead>
    <tbody>
        <?php foreach($data as $k=>$v){?>
            <tr><?php echo $v['id']?></tr>
           <tr><?php echo $v['Manufacturer']?></tr>
           <tr>Actions</tr>
        <?php }?>
    </tbody>
</table>
<?php if(!$ajax){?>
    </div>
<?php }?>
/** This will show pagination link**/
<?php echo $links;?>

Javascript

/** now we will prevent pagination default functionality and make it as ajax **/
$(document).on('click','.pagination li a',function(e){
    e.preventDefault();
    url = $(this).attr('href');    
    $.ajax({
        url:url,
        type:json, 
        success :function(data){
            $(".loadData").html(data);
        }
    });
})
  1. Pagination with datatable (serverside Ajax) and codeigniter.

Include js and css library of dataTable into html file

<script type="text/javascript" src="//code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">

Your html look as below

<table class="table table-condensed table-bordered table-striped" id="example">
    <thead>
       <tr>
           <th>ID</th>
           <th>Manufacturer</th>
           <th>Actions</th>
       </tr>
    </thead>
</table>

Now your ajax call

<script>
        $(document).ready(function() {
            $('#example').DataTable({
                url: '<?php base_url(); ?>controllerName/index',
                processing: true,
                serverSide: true,
                paging: true,
                searching: true,
                ordering: true,
                order: [[0, "asc"]],
                scrollX: true,
                scroller: true,
                columns: [{data: id"}, {data: "manufacturer"}, {data: "action"}]               
            });
        });
    </script>

Controller

public function index() {
if($this->session->userdata('is_logged_in')){
        $data = array();
        if ($this->input->is_ajax_request()) {
            /** this will handle datatable js ajax call * */
            /** get all datatable parameters * */
            $search = $this->input->get('search');/** search value for datatable  * */
            $offset = $this->input->get('start');/** offset value * */
            $limit = $this->input->get('length');/** limits for datatable (show entries) * */
            $order = $this->input->get('order');/** order by (column sorted ) * */
            $column = array('id', 'manufacturer');/**  set your data base column name here for sorting* */
            $orderColumn = isset($order[0]['column']) ? $column[$order[0]['column']] : 'parameter';
            $orderDirection = isset($order[0]['dir']) ? $order[0]['dir'] : 'asc';
            $ordrBy = $orderColumn . " " . $orderDirection;

            if (isset($search['value']) && !empty($search['value'])) {
                /** creat sql or call Model * */

                /** I am calling sql directly in controller for your answer 
                 * Please change your sql according to your table name
                 * */
                $sql = "SELECT * FROM TABLE_NAME WHERE column_name '%like%'" . $search['value'] . " order by " . $ordrBy . " limit $offset,$limit";
                $sql = "SELECT count(*) FROM TABLE_NAME WHERE column_name '%like%'" . $search['value'] . " order by " . $ordrBy;
                $result = $this->db->query($sql);
                $result2 = $this->db->query($sql2);
                $count = $result2->num_rows();
            } else {
                /**
                 * If no seach value avaible in datatable
                 */
                $sql = "SELECT * FROM TABLE_NAME  order by " . $ordrBy . " limit $offset,$limit";
                $sql2 = "SELECT * FROM TABLE_NAME  order by " . $ordrBy;
                $result = $this->db->query($sql);
                $result2 = $this->db->query($sql2);
                $count = $result2->num_rows();
            }
            /** create data to display in dataTable as you want **/    

            $data = array();
            if (!empty($result->result())) {
                foreach ($result->result() as $k => $v) {
                    $data[] = array(
                         'id' =>  $v['id'],
                         'manufacturer'=>$v['manufacturer'],                         
                         'actions' =>  "<a href=''><strong>Edit</strong></a>" 
                    );
                }
            }
            /**
             * draw,recordTotal,recordsFiltered is required for pagination and info.
             */
            $results = array(
                "draw" => $this->input->get('draw'),
                "recordsTotal" => count($data),
                "recordsFiltered" => $count,
                "data" => $data 
            );
            echo json_encode($results);
        } else {
            /** this will load by default with no data for datatable
             *  we will load data in table through datatable ajax call
             */
        $this->load->view('../template/header');
        $this->load->view('manufacturer',$data);
        $this->load->view('../template/footer');

        }
    }else{
        redirect('main/restricted');
    }
}

Datatable will create your pagination.

shafiq.rst
  • 1,286
  • 1
  • 12
  • 26
  • Undefined variable: data and Invalid argument supplied for foreach() I got this error @shafiq I tried your first example – Genina Anne Gabuten Mar 26 '17 at 04:06
  • its not going here if ($this->input->is_ajax_request()) { /*** return only Table view if its ajax call **/ $data['ajax'] = true; echo json_encode($this->load->view('trademark',$data,true)); } – Genina Anne Gabuten Mar 26 '17 at 04:07
  • @GeninaAnneGabuten change this $data = $query->result(); to $data['data'] = $query->result(); if ($this->input->is_ajax_request()) execute only if its ajax call and return table only. We will replace it with javascript – shafiq.rst Mar 26 '17 at 04:22
  • now its not returning data but not on my table its just like this.. 1POWERTRANS KC 51Actions2100Actions3101Actions41031Actions5104Actions6107Actions7108Actions8108-2085--01-HB1Actions91084Actions101168Actions11122Actions12136Actions13137Actions14145Actions151496Actions1615118Actions1715553Actions1815901Actions1916118Actions20162Actions ID Trademark Actions – Genina Anne Gabuten Mar 26 '17 at 04:24
  • On your page load it should go into else statement. Then we are calling it ajax on pagination click. So it should go in if conditions. – shafiq.rst Mar 26 '17 at 04:26
  • what's your URL ? – shafiq.rst Mar 26 '17 at 04:31
  • my current URL is localhost/ci_attl/trademark and this is my controller URL $config['base_url'] = base_url().'trademark/display_trademark'; – Genina Anne Gabuten Mar 26 '17 at 04:33
  • its not showing the
    meaning its not loading the ajax right?
    – Genina Anne Gabuten Mar 26 '17 at 04:37
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/139068/discussion-between-shafiq-and-genina-anne-gabuten). – shafiq.rst Mar 26 '17 at 04:40
0

Have you tried the CodeIgniter Pagination class?

Simon K
  • 1,503
  • 1
  • 8
  • 10