user3155074 user3155074 - 1 year ago 69
jQuery Question

Automatic update table by jQuery

I succeed in populating the table dynamically with JSON data. The problem now is how to update the table with new data every a certain amount of time. I tried to cancel the table before creating a new one with new data, but it seems to not be working. When I try the code below, the table is not populated. Could you help me?

function loadTable(){
$('#mytable tbody tr').remove();
$.getJSON( 'sort.php', function( data ) {
$.each( data, function( i, val ) {
$('#mytable tr').eq(i).after('<tr><td>'+val.value0+'</td><td>'+
val.n_users+ '</td><td>'+val.value1+'/'+val.value2+
'</td><td>10:59 08/01/2014</td></tr>');
});
});
setTimeout("loadTable()",15000);
}

Answer Source

The reason your code does not work, is that you are removing all of the tr elements, and then trying to add code based on tr elements:

$('#mytable tbody tr').remove();

and:

$('#mytable tr').eq(i).after(...);

By this time, there are no tr's, so this line does nothing. Instead, simply append tr's, instead of trying to modify existing ones:

function loadTable() {
    $.getJSON('sort.php', function (data) {
        $('#mytable tbody tr').remove();
        $.each(data, function (i, val) {
            $('#mytable').append('<tr><td>' + val.value0 + '</td><td>' + val.n_users + '</td><td>' + val.value1 + '/' + val.value2 + '</td><td>10:59 08/01/2014</td></tr>');
        });
    });
    setTimeout("loadTable()", 15000);
}

If the number of rows will always be the same, you can modify existing rows, but you need to make sure not to delete them:

function loadTable() {
    $.getJSON('sort.php', function (data) {
        $.each(data, function (i, val) {
            $('#mytable tr').eq(i).html('<td>' + val.value0 + '</td><td>' + val.n_users + '</td><td>' + val.value1 + '/' + val.value2 + '</td><td>10:59 08/01/2014</td>');
        });
    });
    setTimeout("loadTable()", 15000);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download