How to make paging in Codeigniter using AJAX?

Asked

Viewed 1,798 times

4

I’m having trouble finding a way to paginate using AJAX. I’m used to doing it the traditional way and directly with the server using Codeigniter as framework application. However, this time I need it to be done without the refresh page. Below follows 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 the default paging code for Codeigniter. There is another way?

1 answer

6


Use codeigniter pagination integrated 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 pagination

$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);
}

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

<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>

No controller index put everything around #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 some of the ways to do it, but all have in common the ajax request and a controller that brings only what will be replaced on the page.

See also:

Codeigniter with Datatables

Browser other questions tagged

You are not signed in. Login or sign up in order to post.