Comment recharger les données DataTables(jquery)?

comment recharger l'onglet sélectionné? En fait, j'ai un problème avec le rechargement de la pièce. Lorsque j'ajoute mes données, je vais enregistré avec succès dans datable mais dans le champ id dans la base de données, il montre l'id approprié, mais quand j'ajoute le détail il ne montre pas l'id dans datable.

(avant de rafraîchir l'onglet résumé) voici un exemple il montre quelque chose comme ceci dans datable id patient mari age ...........so on... "XYZ abc 23....... ainsi de suite...

<!-(Après rafraîchissement manuel) mais quand je rafraîchis mon page de montrer avec succès..comme ceci dans datable: id patient mari âge ...........so on... 13 XYZ abc 23 ....... ainsi de suite...

mais exactement je veux quand j'ajoute mon détail il devrait automatiquement rafraîchir l'onglet sélectionné.

Mon code est ci-dessous:

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

    }
    });

j'ai également fatigué cette approche, mais pas de succès.

je veux que mon datatable rafraîchisse les données

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() ]);
    }
});
18
demandé sur Alexander Farber 2011-04-06 16:44:43

10 réponses

Vous pouvez utiliser une approche simple...

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

Il va rafraîchir les données en effectuant une requête ajax avec les mêmes paramètres. Très simple.

27
répondu Elior Cohen 2012-10-13 20:00:54

Vous pouvez utiliser cette fonction:

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

Ne pas oublier de l'appeler après votre fonction de suppression a réussi.

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

19
répondu Edgar Villegas Alvarado 2011-05-03 14:45:28

Utiliser le fnReloadAjax() par le DataTables.net auteur.

je copie le code source ci - dessous-au cas où l'original bouge:

$.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();
13
répondu Alexander Farber 2012-05-03 13:50:28

solution plus simple:

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

$.getJSON(url, null, function (json) {
    dt.fnClearTable();
    dt.fnAddData(json.aaData);
    dt.fnDraw();
});
7
répondu Onur Yıldırım 2014-02-21 19:09:08

si quelque chose fonctionne! Faire ceci:

exemple:

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

comment recharger la table:

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

initTable est juste une méthode, qui a initialisé la Table avec getJSON.

6
répondu Masood Moshref 2012-10-13 10:42:53

aucune de ces solutions n'a fonctionné pour moi, mais j'ai fait quelque chose de semblable à la réponse de Masood. Ici, c'est pour la postérité. Cela suppose que vous avez <table id="mytable"></table> dans votre page quelque part:

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

Les pièces importantes sont:

  1. bDestroy, qui efface la table courante avant de la charger.
  2. hide() et fnInitComplete, ce qui garantit que la table n'apparaît qu'après que tout est chargé. Sinon, il se redimensionne et semble bizarre tandis que chargement.

il suffit d'ajouter l'appel de fonction à $(document).ready() et vous devriez être tous ensemble. Il chargera la table d'abord, ainsi que recharger plus tard sur un clic de bouton ou quoi que ce soit.

3
répondu Josh 2014-05-09 15:29:59
// 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();
    });
}
2
répondu Martin 2012-03-21 07:07:20

je poste ceci juste au cas où quelqu'un en aurait besoin..

il suffit de créer un bouton:

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

mais n'oubliez pas d'ajouter ceci lorsque vous appelez le datatable:

mytable = $("#mytable").dataTable();
2
répondu iguider 2014-03-19 19:39:32

pour recharger les données de la table à partir de la source de données Ajax, utilisez la fonction suivante:

dataTable.ajax.reload()

dataTable est la variable utilisée pour créer la table.

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

Voir ajax.reload() pour plus d'informations.

1
répondu Pablo Palladino 2015-08-06 20:49:51

Pour les versions plus récentes d'utilisation:

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

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

extrait de:https://stackoverflow.com/a/27781459/4059810

1
répondu ChrisE 2017-05-23 11:53:18