Update datatables when button is clicked

Update datatables when button is clicked

dimmatdimmat Posts: 2Questions: 0Answers: 0
edited April 2012 in General
I've created a simple form and I'm using datatables to display some data. Data are being populated by a php script (process.php) which returns the proper results in JSON format. In the form, there is a button that sends the value of the textbox to the process.php. The problem is that I cannot update/alter datatable with the new data received by process.php script when the button is clicked.

The code of the form:

[code]

Enter an id:








id
Surname
Name



<!-- data goes here -->



[/code]

To create the datatable, I'm using the following JQuery code:

[code]
$(document).ready(function() {
var oTable = $('#example').dataTable( {
"sPaginationType": "full_numbers",
"iDisplayLength": 10,
//"bServerSide": true, (when enabled, I get errors)
"sAjaxSource": "process.php"
} );

$("#btnSubmit").click(function(){
$.ajax({
type: "POST",
url: "process.php",
data: "txtId=" + $("txtId").val(),
success: function(result) {
oTable.fnReloadAjax();
oTable.fnDraw();
}
});
});
} );
[/code]

process.php script (works fine) is:

[code]
<?php
$result="";
if (empty($_REQUEST["txtId"])) {
$result = '{"aaData":[["1","Surname1","Name1"]]}';
}
else {
$result = '{"aaData":[["2","Surname2","Name2"]]}';
}
print $result;
?>
[/code]

Replies

  • dimmatdimmat Posts: 2Questions: 0Answers: 0
    edited April 2012
    At last, I found the solution! There were 2 problems in my JQuery code:

    1. I had to add the fnReloadAjax() code after the script tags which load datatables and before the $(document).ready() statement.
    2. I had to alter the JQuery code of my submit button (no need for an AJAX call, only fnReloadAjax() is necessary).

    JQuery code now is:

    [code]
    //
    // fnReloadAjax()
    //
    $.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
This discussion has been closed.