HoodCoderMan HoodCoderMan - 4 months ago 29
jQuery Question

JQUERY AJAX call function on timeout

I am trying to reload my JQUERY DATATABLE without refreshing the page in an attempt to capture new data.

Here is my initial READY function that begins the process:

$(document).ready(function()
{
$.ajax({
url:'api/qnams_all.php',
type:"GET",
dataType:"json"
}).done(function(response) {
console.log(response.data);
renderDataTable(response.data)
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
});
});


I'm sending the data to this function:

function renderDataTable(data)
{
var $dataTable = $('#example1').DataTable({
"data": data,
"iDisplayLength": 25,
"order": [[ 6, "desc" ]],
"bDestroy": true,
"stateSave": true
// there's some more stuff, but I don't think necessary to show
});
}


I'm trying to utilize the answer found here: How to refresh table contents in div using jquery/ajax

As follows:

setTimeout(function(){
$( "#example1" ).load( "mywebpage.php #example1" );
}, 2000);


Using all of the above code, when the page first loads, it looks like this:

enter image description here

But after the refresh, it looks like this:

enter image description here

The pic immediately above does indeed reload without the page refreshing, but I'm not sure why it looks like the pic above.

Please help me fix this.

Answer

I think this example will be usefull

//Reload the table data every 30 seconds (paging reset)
var table = $('#example').DataTable( {
    ajax: "data.json"
} );

setInterval( function () {
    table.ajax.reload();
}, 30000 );

more details - here

Comments