fnReloadAjax - Count rows before & after

fnReloadAjax - Count rows before & after

j7mboj7mbo Posts: 7Questions: 0Answers: 0
edited November 2012 in General
I'm trying to tell if an ajax request has pulled new rows, and refresh the page if it has.

[code]
// AJAX this and get results to repopulate table every 10 seconds
setInterval(function() {

// Get the old length
var oTable = $('.dataTable').dataTable();
oldLength = oTable.fnGetData().length;
console.log('Old: '+oldLength);

// AJAX it
oTable.fnReloadAjax();

// Get the new length
oTable = $('.dataTable').dataTable();
newLength = oTable.fnGetData().length;
console.log('New: '+newLength);

// If any changes have been made, reload page
if(oldLength != newLength)
{
//document.location.reload();
console.log('CHANGED');
}
}, 10000);
[/code]

The two console.logs's ALWAYS show the same number. Why aren't they getting the length correctly?

Replies

  • allanallan Posts: 63,530Questions: 1Answers: 10,473 Site admin
    Because the ajax request is async. Your second length 'get' is running before the new data has been loaded, so you need to use a callback function to have it happen when the new data has loaded. For example:

    [code]
    // AJAX this and get results to repopulate table every 10 seconds
    setInterval(function() {

    // Get the old length
    var oTable = $('.dataTable').dataTable();
    oldLength = oTable.fnGetData().length;
    console.log('Old: '+oldLength);

    // AJAX it
    oTable.fnReloadAjax( null, function () {
    // Get the new length
    oTable = $('.dataTable').dataTable();
    newLength = oTable.fnGetData().length;
    console.log('New: '+newLength);

    // If any changes have been made, reload page
    if(oldLength != newLength)
    {
    //document.location.reload();
    console.log('CHANGED');
    }
    } );
    }, 10000);
    [/code]

    Allan
  • j7mboj7mbo Posts: 7Questions: 0Answers: 0
    Excellent, I was looking for a callback but wasn't quite sure how to implement it. Thanks!
This discussion has been closed.