How to refresh table properly?

How to refresh table properly?

PWHPWH Posts: 26Questions: 5Answers: 0

I am trying to create a table which calls an api every x seconds.I am trying 2 methods. 1st is the setInterval( function () which when run, works first time but on the update, I get an invalid json response warning and the table does not update.
The second method, updates the table but adds an extra row of each item on each update. What I am after is to refresh the table. What am I doing wrong?
Code for setInterval

$(document).ready(function() {
    //setTimeout(fetchdata,5000);
    var table = $('#example').DataTable({
        
        columns: [
            { data: 'name' },
            { data: 'price'},
            { data: 'initialprice'},
            { data: 'high'},
            { data: 'low'},
            { data: 'volume'},
            { data: 'bid'},
            { data: 'ask'}
            ],
            "columnDefs": [
            //{ "visible": false, "targets": 0 } // can hide columns with this..
            ],
                rowGroup: {dataSrc: 5},
                    //"displayLength": 15,
                    "order": [[ 0, 'asc' ]], // Sort Order
                    //  orderFixed: [[0, 'asc']],
                   
                    "drawCallback": function ( settings ) {
                    var api = this.api();
                    var rows = api.rows( {page:'current'} ).nodes();
                    var last=null;
 
                    api.column(0, {page:'current'} ).data().each( function ( group, i ) {
                    group = (group.substr(group.length0,3)); // Substring BTC
                    if ( last !== group) {
                    $(rows).eq( i ).before(
                        '<tr class="group"><td colspan="1">'+group+'</td></tr>'
                    );
 
                    last = group;
                }
            } );
        }
    } );
        $.ajax({
        url: "https://tradeogre.com/api/v1/markets",
        type: 'get',
        dataType: 'json',
        success: function(data){
        // Perform operation on return value
                var dt_data = [];
      
                for (var i=0; i<data.length; i++) {
                  var coin_name = Object.keys(data[i])[0];
                  var market = data[i][coin_name];
                  
                  market.name = coin_name;
                  dt_data.push(market);
                }  
            console.log(dt_data);
            table.rows.add( dt_data ).draw();
        }
        });
        setInterval( function () {
        table.ajax.reload();
        }, 30000 );
});

Code for second method.

$(document).ready(function() {
setTimeout(fetchdata,5000);
    var table = $('#example').DataTable({
        
        columns: [
            { data: 'name' },
            { data: 'price'},
            { data: 'initialprice'},
            { data: 'high'},
            { data: 'low'},
            { data: 'volume'},
            { data: 'bid'},
            { data: 'ask'}
            ],
            "columnDefs": [
            //{ "visible": false, "targets": 0 } // can hide columns with this..
            ],
                rowGroup: {dataSrc: 5},
                    //"displayLength": 15,
                    "order": [[ 0, 'asc' ]], // Sort Order
                    //  orderFixed: [[0, 'asc']],
                   
                    "drawCallback": function ( settings ) {
                    var api = this.api();
                    var rows = api.rows( {page:'current'} ).nodes();
                    var last=null;
 
                    api.column(0, {page:'current'} ).data().each( function ( group, i ) {
                    group = (group.substr(group.length0,3)); // Substring BTC
                    if ( last !== group) {
                    $(rows).eq( i ).before(
                        '<tr class="group"><td colspan="1">'+group+'</td></tr>'
                        //$('table.display').dataTable();
                    );
 
                    last = group;
                }
            } );
        }
    } );
    
    function fetchdata(){
        $.ajax({
        url: "https://tradeogre.com/api/v1/markets",
        type: 'get',
        dataType: 'json',
        success: function(data){
        // Perform operation on return value
                var dt_data = [];
      
                for (var i=0; i<data.length; i++) {
                  var coin_name = Object.keys(data[i])[0];
                  var market = data[i][coin_name];
                  
                  market.name = coin_name;
                  dt_data.push(market);
                }  
            console.log(dt_data);
            table.rows.add( dt_data ).draw();
        },
        complete:function(data){
        setTimeout(fetchdata,5000);
        
        }
        });
    }
});

Thank you

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,167Questions: 26Answers: 4,921
    Answer ✓

    works first time but on the update, I get an invalid json response warning and the table does not update.

    Did you follow the troubleshooting steps at the link provided in the error?
    https://datatables.net/manual/tech-notes/1

    You will need to determine what in the response is invalid.

    The second method, updates the table but adds an extra row of each item on each update.

    Use the clear() API to clear the table before using table.rows.add( dt_data ).draw();.

    Kevin

  • PWHPWH Posts: 26Questions: 5Answers: 0

    Thank you Kevin, I have it working with the clear() method. I did look at
    https://datatables.net/manual/tech-notes/1 but to my eyes, the data looked jast the same after every refresh
    Thank you again for your help. My little table is starting to work!

This discussion has been closed.