18

How to reload the selected tab? Actually I have problem with reloading part. When I add my data I'll successfully saved in datatable but in id field in database it shows proper id, but when I add the detail its not shows id in datatable.

(before refresh the summary tab) here is example it shows something like this in datatable id patient husband age ...........so on... '' xyz abc 23....... so on...

(after refreshing manually) but when I refresh my page it show successfully..like this in datatable: id patient husband age ...........so on... 13 xyz abc 23 ....... so on...

But exactly I want when I add my detail it should automatically refresh the selected tab.

My code is below:

<button type="button"  a href="javascript:void(0);" onclick="fnClickAddRow();">Add Summary</button>

function fnClickAddRow(event) {

$('#table_scroll').dataTable().fnAddData( [

$('#patientt').val(),$('#husband').val(),$('#age').val(),$('#opu_no').val(),$('#date').val(),$('#proc').val(),$('#no_of_eggs').val(),$('#fert').val(),$('#et_date').val(),$('#et_day').val(),$('#et').val(),$('#fz').val(),$('#bioch_preg').val(),$('#clin_preg').val(),$('#fh').val(),$('#comment').val()

]);


var datastring = $(Form_summary).serialize();

$.ajax({
    type: "POST",
    url: "summaryajax.php",
    data: datastring, 
    success: function(response){

 alert(response);

    }
    });

I also tired this approach but no success.

I want my datatable to refresh the data

function fnClickAddRow(event) {

var datastring = $(Form_summary).serialize();

$.ajax({
    type: "POST",
    url: "summaryajax.php",
    data: datastring, 
    success: function(response){
       $('#table_scroll').dataTable().fnAddData( 
          [resposne, $('#patientt').val(), $('#husband').val(),$('#age').val(),
            $('#opu_no').val(), $('#date').val(),$('#proc').val(), $('#no_of_eggs').val(), 
            $('#fert').val(),$('#et_date').val(), $('#et_day').val(), $('#et').val(), 
            $('#fz').val(), $('#bioch_preg').val(), $('#clin_preg').val(), $('#fh').val(), 
            $('#comment').val() ]);
    }
});
Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
gur
  • 191
  • 1
  • 1
  • 5

10 Answers10

28

You can use a simple approach...

$('YourDataTableID').dataTable()._fnAjaxUpdate();

It will refresh the data by making an ajax request with the same parameters. Very simple.

Sven
  • 69,403
  • 10
  • 107
  • 109
Elior Cohen
  • 281
  • 3
  • 2
  • 1
    Doesn't work for me; it makes the back-end call and gets the data but doesn't recreate the table itself. :( – Josh May 09 '14 at 15:06
  • 2
    dude, you are a major life saver! this works perfectly for me. +100 – Eman Jun 20 '14 at 18:34
19

You could use this function:

function RefreshTable(tableId, urlData)
    {
      //Retrieve the new data with $.getJSON. You could use it ajax too
      $.getJSON(urlData, null, function( json )
      {
        table = $(tableId).dataTable();
        oSettings = table.fnSettings();

        table.fnClearTable(this);

        for (var i=0; i<json.aaData.length; i++)
        {
          table.oApi._fnAddData(oSettings, json.aaData[i]);
        }

        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        table.fnDraw();
      });
    }

Dont' forget to call it after your delete function has succeded.

Source: http://www.meadow.se/wordpress/?p=536

Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
13

Use the fnReloadAjax() by the DataTables.net author.

I'm copying the source code below - in case the original ever moves:

$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )
{
    if ( typeof sNewSource != 'undefined' && sNewSource != null )
    {
        oSettings.sAjaxSource = sNewSource;
    }
    this.oApi._fnProcessingDisplay( oSettings, true );
    var that = this;
    var iStart = oSettings._iDisplayStart;
    var aData = [];

    this.oApi._fnServerParams( oSettings, aData );

    oSettings.fnServerData( oSettings.sAjaxSource, aData, function(json) {
        /* Clear the old information from the table */
        that.oApi._fnClearTable( oSettings );

        /* Got the data - add it to the table */
        var aData =  (oSettings.sAjaxDataProp !== "") ?
            that.oApi._fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ) : json;

        for ( var i=0 ; i<aData.length ; i++ )
        {
            that.oApi._fnAddData( oSettings, aData[i] );
        }

        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        that.fnDraw();

        if ( typeof bStandingRedraw != 'undefined' && bStandingRedraw === true )
        {
            oSettings._iDisplayStart = iStart;
            that.fnDraw( false );
        }

        that.oApi._fnProcessingDisplay( oSettings, false );

        /* Callback user function - for event handlers etc */
        if ( typeof fnCallback == 'function' && fnCallback != null )
        {
            fnCallback( oSettings );
        }
    }, oSettings );
}

/* Example call to load a new file */
oTable.fnReloadAjax( 'media/examples_support/json_source2.txt' );

/* Example call to reload from original file */
oTable.fnReloadAjax();
Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
  • 2
    fnReloadAjax() worked perfectly. I didn't find this solution anywhere. It keeps all active filter and sorting. Just perfect. – Rui Marques Jul 10 '12 at 22:06
  • This is a good way of doing it. Works perfectly, but it seems to me that Elior Cohen's answer is better. The result is the same, but it doesn't require any kind of extra code, just a simple datatables method call. Go for $('YourDataTableID').dataTable()._fnAjaxUpdate(); – Felipe Leão Jan 29 '14 at 19:22
  • 1
    In principle similar logic was added to DataTable v1.10.1 as [`ajax.reload()`](http://datatables.net/reference/api/ajax.reload%28%29). – dma_k Jul 17 '14 at 14:49
8

Simpler solution:

var dt = $('#table_scroll').dataTable();

$.getJSON(url, null, function (json) {
    dt.fnClearTable();
    dt.fnAddData(json.aaData);
    dt.fnDraw();
});
Onur Yıldırım
  • 32,327
  • 12
  • 84
  • 98
6

If anything works! Do this:

example:

<div id="tabledisplay"><table class="display" id="table"></table><table </div>

how to reload the table:

$('#tabledisplay').empty();
$('#tabledisplay').append("<table class=\"display\" id=\"table\"></table>");
initTable( "tablename");  

initTable is just a method, that initialized the Table with getJSON.

Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
Masood Moshref
  • 370
  • 4
  • 9
3

None of these solutions worked for me, but I did do something similar to Masood's answer. Here it is for posterity. This assumes you have <table id="mytable"></table> in your page somewhere:

function generate_support_user_table() {
        $('#mytable').hide();
        $('#mytable').dataTable({
            ...
            "bDestroy": true,
            "fnInitComplete": function () { $('#support_user_table').show(); },
            ...
        });
}

The important parts are:

  1. bDestroy, which wipes out the current table before loading.
  2. The hide() call and fnInitComplete, which ensures that the table only appears after everything is loaded. Otherwise it resizes and looks weird while loading.

Just add the function call to $(document).ready() and you should be all set. It will load the table initially, as well as reload later on a button click or whatever.

Josh
  • 6,944
  • 8
  • 41
  • 64
2

I'm posting this just in case someone need it..

Just create a button:

<button type="button" href="javascript:void(0);" onclick="mytable.fnDraw();">Refresh</button>

but don't forget to add this when calling the datatable:

mytable = $("#mytable").dataTable();
Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
iguider
  • 721
  • 1
  • 12
  • 25
2
// Get the url from the Settings of the table: oSettings.sAjaxSource

function refreshTable(oTable) {
    table = oTable.dataTable();
    oSettings = table.fnSettings();

    //Retrieve the new data with $.getJSON. You could use it ajax too
    $.getJSON(oSettings.sAjaxSource, null, function( json ) {
        table.fnClearTable(this);

        for (var i=0; i<json.aaData.length; i++) {
            table.oApi._fnAddData(oSettings, json.aaData[i]);
        }

        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        table.fnDraw();
    });
}
Martin
  • 21
  • 1
1

To reload the table data from Ajax data source, use the following function:

dataTable.ajax.reload()

Where dataTable is the variable used to create the table.

var dataTable = $('#your_table_id').DataTable({
     ajax: "URL"
});

See ajax.reload() for more information.

Gyrocode.com
  • 57,606
  • 14
  • 150
  • 185
1

For the newer versions use:

var datatable = $('#table').dataTable().api();

$.get('myUrl', function(newDataArray) {
    datatable.clear();
    datatable.rows.add(newDataArray);
    datatable.draw();
});

Taken from: https://stackoverflow.com/a/27781459/4059810

Community
  • 1
  • 1
ChrisE
  • 376
  • 4
  • 14