Question

[Solved] reload datatable after ajax success

I use JQuery DataTable. I send data to datatable onclick in json file at ajax succes .the first click everything is good,But the next click I get only the right data ANd wrong value of dataTables_info it display always the first value of dataTables_info And paginatio AND row too from the first result.
This is the first display of data in datatable:

The first Click

ALL the next Click I get only right data:
For this exemple they are one result showing in picture below but everything else(info ,show,pagination) belong to first search showing in the first picture :
enter image description here

In the second Exemple When I click at any page of pagination I get the content of the first page result!!
This is my function ONclick:

    $ ( '#ButtonPostJson' ).on('click',function() {

             $("tbody").empty();
             var forsearch = $("#searchItem").val();

    $.ajax({
        processing: true,
        serverSide: true,
        type: 'post',
        url: 'searchData.json',
        dataType: "json",
        data: mysearch,
       /* bRetrieve : true,*/

        success: function(data) {
            $.each(data, function(i, data) {
                var body = "<tr>";
                body    += "<td>" + data.name + "</td>";
               ..........................
               ..........................
                body    += "</tr>";
                $('.datatable-ajax-source table').append(body);

            })
        ;
            /*DataTables instantiation.*/
     $('.datatable-ajax-source table').dataTable();
    },

        error: function() {
            alert('Processus Echoué!');
        },
        afterSend: function(){
    $('.datatable-ajax-source table').dataTable().reload();
 /* $('.datatable-ajax-source table').dataTable({bRetrieve : true}).fnDestroy();    
    $(this).parents().remove(); 
$('.datatable-ajax-source table').dataTable().clear();*/
    }
    });
    });

I try everything and i dont know what I miss.
I use this jquery for datatable:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>

Thanks.

Solution #1:

On a button clik you dont need to empty your table body and make initiate the datatable again with the ajax.

you just have to call your ajax again as you have already initiate on document ready function

just use

$("#Table_id").ajax.reload();

check the below link, you will have better idea.

https://datatables.net/reference/api/ajax.reload()

Let me know if this doesn’t help you

Respondent: MedKostali

Solution #2:

Use like it

$('#product_table').DataTable().ajax.reload();
Respondent: Punit Gajjar

Solution #3:

I created this simple function:

function refreshTable() {
  $('.dataTable').each(function() {
      dt = $(this).dataTable();
      dt.fnDraw();
  })
}
Respondent: Waqar Sharif

Solution #4:

use below code..it perfectly work, it keep your pagination without lose current page

$(“#table-example”).DataTable().ajax.reload(null, false );

Solution #5:

I had this same problem. I found a function I wrote on a project that deals with this. Here is a simple 2 column table I made.

<table id="memberships" class="table table-striped table-bordered table-hover"  width="100%">
        <thead>
            <tr>
                <th>Member Name</th>
                <th>Location</th>
            </tr>
        </thead>
        <tfoot>
          <tr>
            <th>Member Name</th>
            <th>Location</th>
          </tr>
        </tfoot>
      </table>

This is my script to populate it:

function drawTable(){
var table = $('#memberships').DataTable();

table.destroy();

value = $("#memberName").val();
console.log("member name-->>" + value);
$('#memberships').DataTable({
responsive:true,
pageLength: 50,
ajax:{
    "url": `//BACKEND API CALL`,
    "type":"get",
    "dataSrc": 'members'//my data is in an array called members
},
columns: [
  {"data": "name_display" },
  {"targets": 0,
    "data": "membershipID",
    "render": function ( data, type, full, meta ) {
      return '<button type="button" class="btn btn-info btn-block" 
      onclick="editMember(' + data + ')">Edit Member</button><button 
      type="button" class="btn btn-danger btn-block" 
      onclick="deleteMember(' + data + ')">Delete</button>';
    }
  }
 ]
});
$.fn.dataTable.ext.errMode = 'none';
}

You can ignore my column render function. I needed 2 buttons based on the data returned. The key was the table.destroy in the function. I created the table in a variable called table. I destroy it right in this initialization because it allowed me to use this same function over and over. The first time it destroys an empty table. Each call after that destroys the data and repopulates it from the ajax call.

Hope this helps.

Update: After playing with datatables alot more I found that setting table to a variable in a global scope to your function allows you to use reload.

var table = $('#memberships').DataTable({});

Then

table.ajax.reload();

should work.

Respondent: salithlal

Solution #6:

$("#Table_id").ajax.reload(); did not work.

I implemented –

var mytbl = $("#Table_id").datatable();
mytbl.ajax.reload;
Respondent: sixstring

Solution #7:

.reload() is not working properly untill we pass some parameter

var  = $("#example").DataTable() ;
datatbale_name.ajax.reload(null, false );
Respondent: Adarsh Madrecha

Solution #8:

Try This i hope it will work

$(“#datatable_id”).DataTable().ajax.reload();

Respondent: Mabd

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy