How to do pagination in CodeIgniter using AJAX?

4

I'm having a hard time finding a way to do paging using AJAX. I am accustomed to doing it both traditionally and directly with the server using Codeigniter as the application framework . However, this time I need it done without the refresh of the page. Below is the pagination code made in Codeigniter. What is the correct way to use AJAX for this application?

# Preparando o limite da paginação

        $de_paginacao = ( $de_paginacao < 0 || $de_paginacao == 1 ) ? 0 : (int) $de_paginacao;

        # Carrega a biblioteca

        $this->load->library(array('pagination'));

        # Acessa o Model, executa a função get_all() e recebe os contatos

        $pedidos = $this->model_pedido->get_all($de_paginacao, $this->pedidos_pagina);

        # Paginação

        $config_paginacao['base_url'] = site_url('admin/all/');
        $config_paginacao['total_rows'] = $this->model_pedido->count_rows();
        $config_paginacao['per_page'] = 10;

        $this->pagination->initialize($config_paginacao);

        $dados['html_paginacao'] = $this->pagination->create_links();

NOTE: This is Codeigniter's default paging code. Is there another way?

    
asked by anonymous 24.12.2013 / 12:03

1 answer

6

Use the integrated codeigniter pagination with jquery.

First add this javascript to your head:

  <script type="text/javascript">
  $(function() {
      $("#ajax_paging a").click(function() {
        var url = $(this).attr("href");
        $.ajax({
          type: "POST",
          data: "ajax=1",
          url: url,
          beforeSend: function() {
            $("#content").html("");
          },
          success: function(msg) {
            $("#content").html(msg);
          }
        });
        return false;
      });
    }
  });
  </script>

In the controller that generates the paging

$dados['html_paginacao'] = $this->pagination->create_links();
if ($this->input->post('ajax')) {
    $this->load->view('contato/ajax_index', $dados);
} else {
    $this->load->view('contato/index', $dados);
}

Notice that depending on the request we load a different view. The view ajax_index is minimalist and contains only what will be replaced, eg:

<div id="data">
  <?php foreach($contato['nome'] as $u): ?>
      <div><?php echo $u; ?></div>
  <?php endforeach; ?>
</data>

<div id="ajax_paging">
  <?php echo $pagination; ?>
</div>

In the controller index, put everything around the #content

...
<div id="content">
    <div id="data">
      <?php foreach($contato['nome'] as $u): ?>
          <div><?php echo $u; ?></div>
      <?php endforeach; ?>
    </data>

    <div id="ajax_paging">
      <?php echo $pagination; ?>
    </div>
</div>
...

This is just a few of the ways to do it, but all have the ajax request in common and a controller that brings only what will be replaced on the page.

See also:

Codeigniter with Datatables

    
24.12.2013 / 14:20