always-a-learner
always-a-learner

Reputation: 3794

data getting lost after any operation on data-table while loading rows using ajax

I am fetching dataTable rows using Ajax from my controller in CodeIgniter.

I have fetched it successfully, but the problem is rows get lost while doing any operation on dataTable like sorting, searching. But after refreshing a page it came back.

Here is my Ajax Script:

$('#dataTable_choose').DataTable({
     responsive: true   
});

$('body').on('click', '.getJobApplication', function(e) {

    //alert();

    var noteId = $(this).data('noteId');    
    var note_id = { id : noteId }

     $.ajax({         
    type: 'POST',
    async: true,
    dataType: 'Json',         
    url: get_table_rows,
    data: note_id,
    success: function (response) {                   

        if(response.length > 0){  

        for (i = 0; i < response.length; i++) {   

      innerhtml += "<tr>" +
        "<td>"+response[i].column1+"</td>" +
        "<td>"+response[i].column2+"</td>" +
        "<td>"+response[i].column3+"</td>" +
        "<td>"+response[i].column4+"</td>" +
        "<td><span class='label label-info'>"+column5+"</span></td>" +
        "<td>"+
        "<button type='button' class='btn btn-success waves-effect waves-light' data-secid="+response[i].id2+" " +
        " data-fiid = "+response[i].id+" >Choose</button>" +
        "</td>" +                               
        "</tr>";

        $('#table_body').html(innerhtml);
        }

        } else {
            console.log('error');
        }       

    },
    error: function (msg)
    {
        console.log('error');
    }

 });    

});

Here is the Table HTML Code:

<table id="dataTable_choose" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0"  width="100%">
    <thead>
    <tr>
        <th>Job Title</th>
        <th>Qualification</th>
        <th>Qualification Major</th>
        <th>Candidate Name</th>
        <th>Status</th>
        <th>Action</th>                                    
    </tr>
    </thead>
    <tbody id="table_body">

    </tbody>
</table>

Upvotes: 1

Views: 330

Answers (1)

GeorgeGeorgitsis
GeorgeGeorgitsis

Reputation: 1262

After changing your DataTable's content with ajax, you need to clear the DataTable and redraw it. Below is a code that works for me (tried to add your ID's, please verify that they are correct and implement right in your code):

success: function (response) {
  //DRAW YOUR innerhtml HERE, as you already do
  $("#dataTable_choose").dataTable().fnClearTable(); //clear the table
  $('#dataTable_choose').dataTable().fnDestroy(); //destroy the datatable
  $('#table_body').html(innerhtml);  //add your new data
  $('#dataTable_choose').DataTable({  //redraw with new data
      //YOUR OPTIONS HERE
  });
});

Upvotes: 1

Related Questions