Reloading a datatable without refreshing with ajax

2019-06-12 08:15发布

问题:

I have a datatable in a tab that is loaded from data sended by the controller on index method.

$data = array(
    'documents'      => $this->getDocuments(),
     //more stuff...
);

$this->load->view($this->config->item('groupViews') . 'example/example_edit_view', $data);

I have the view for loading the datatable

<div class="form-group col-md-12">
    <table
        id="t_documents"
        class="table table-striped table-bordered table-hover"
        cellspacing="0"
        width="100%">
     </table>
</div> 

then I load the datatable in javascript when the page is loaded

var documentos = <?php echo json_encode($documents); ?>;
    if ( documentos !== null){
        var table = $('#t_documents').DataTable( {
            language: {
                "url": "<?=trad($this,'LANG_DATATABLES');?>"
     },
     data: documents,
     paging: true,
     ordering: true,
     pageLength: 10,
     columns: [
         { title: "" },    //Download button
         { title: "<?=trad($this,'FILE_NAME');?>" },
         { title: "<?=trad($this,'FILE_TYPE');?>" },
         { title: "" }     //Delete button
     ]
   });
}

I have a delete function too. How can I reload the data (using ajax for getting the data from controller again) without reloading the page?

回答1:

      var table=$('#tableid');
$('#tableid').on('click','thedeletebuton_id',function(event) {
      event.preventDefault();
      var id=$(this).data('id'); // pass the id to the controller to delete using ajax
       $.ajax({
           type: "POST",
           url: "<?php echo base_url('your controller'); ?>",
           data:  {id:id}, 
           success: function(data)
           {
            table.ajax.reload();   /// reloads the table
            alert('Deleted');
           }
       });

      });