HoodCoderMan HoodCoderMan - 1 year ago 111
Ajax Question

jQuery DataTables duplicates are initially loading

So, adding on to my question from yesterday: JQUERY AJAX call function on timeout

Using the first answer from the post from yesterday, the table does indeed reload without refreshing the whole page. It does so after 30 seconds.

But my problem lies before the first refresh...

The page loads, and the records are duplicated. But after the first refresh and every refresh after (unless I manually refresh using F5), everything is fine. No duplicates.

I'm trying to figure out why there are duplicates and how to remove the duplicates upon the page's initial ready event.

Here is the code, starting with the ready event:

}).done(function(response) {
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );

Here is the function to load the DataTable:

function renderDataTable(data)
var $dataTable = $('#example1').DataTable({
"ajax": 'api/qnams_all.php', // just added this
"data": data,
"bDestroy": true,
"stateSave": true

// then I add the reload function

setInterval( function () {
}, 30000 );


As stated above, the setInterval function works like how it should. It's just the initial page load is duplicating all of the records.

Does anyone see why and how to fix it?

Answer Source

I think you've got some duplication going on. You don't need to load the ajax flie and then load it again when you set up the DataTable.

Try replacing all of your code with this:

$(document).ready(function() {
  // load and render the data
  var $dataTable = $('#example1').DataTable({
    "ajax": 'api/qnams_all.php', // just added this
    "data": data,
    "bDestroy": true,
    "stateSave": true,
    // the init function is called when the data table has finished loading/drawing
    "init": function() {
      // now that the initial data has loaded we can start the timer to do the refresh
      setInterval(function() {
      }, 30000);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download