Reload/refresh data using table.ajax.reload()

Reload/refresh data using table.ajax.reload()

JeremyRankJeremyRank Posts: 2Questions: 1Answers: 0

I am struggling on getting the table.ajax.reload to work. I am sure I am missing some parameters. I tried adding the ajax portion to the DataTable section but can't seem to get it to work. Please assist. Below is the code I have.

<script type="text/javascript" class="init">
// The number of milliseconds (ms) when we should update our currency

// charts = one minute
let UPDATE = 60 * 1000;

$(document).ready(function() {
$.ajax({
url: "https://api.coinmarketcap.com/v1/ticker/?limit=0",
type: "Get",
data: {},
success: function (data) {
table = $('#coinTable').DataTable( {
colReorder: {
realtime: true
},
data: data,
"aoColumns" : [
{data : 'price_usd'},
{data : 'percent_change_1h'},
{data : 'percent_change_24h'},
{data : 'percent_change_7d'},
{data : 'market_cap_usd'}
]
} );
}
} );
} );

setInterval( function () {
table.ajax.reload(null, false);
}, UPDATE );

</script>

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,292Questions: 26Answers: 4,944

    You need to use the Datatables ajax for the ajax request. DataTables has no ajax configuration information since you are using jQuery ajax directly.

    Kevin

  • Johannes B.Johannes B. Posts: 7Questions: 1Answers: 0

    Could you try this?

            table.on( 'select', function () {
                    table.ajax.reload();
            } );
    
            table.on( 'deselect', function () {
                    table.ajax.reload();
            } );
    
    

    This should reload the data every time you select a record.

    If this works you could try to add a function which you call from
    the body element.

    <body onload="updatecurrency(); setInterval('updatecurrency()', 1000 )">
    
    
  • JeremyRankJeremyRank Posts: 2Questions: 1Answers: 0

    I did the following as well and that didn’t work.

    $(document).ready(function() {
    $.ajax({
    url: "https://api.coinmarketcap.com/v1/ticker/?limit=0",
    type: "Get",
    data: {},
    success: function (data) {
    table = $('#coinTable').DataTable( {
    ajax: {
    url: same as above,
    type: “Get” },
    colReorder: {
    realtime: true
    },
    data: data,
    "aoColumns" : [
    {data : 'price_usd'},
    {data : 'percent_change_1h'},
    {data : 'percent_change_24h'},
    {data : 'percent_change_7d'},
    {data : 'market_cap_usd'}
    ]
    } );
    }
    } );
    } );

    Thanks for all the help

  • kthorngrenkthorngren Posts: 21,292Questions: 26Answers: 4,944
    Answer ✓

    You need to remove the jQuery ajax() function and just use Datatables. I copied and fixed your code here:
    http://live.datatables.net/sidesiwo/1/edit

    Looks like there are a couple rows with empty data (the first two displayed) and you may want to add more columns for the name, etc.

    Kevin

  • karthikchebrolukarthikchebrolu Posts: 3Questions: 0Answers: 0

    Kindly help me the issue that i am facing relating to the above query. I am new to DataTables. I am loading table data from my jsp. I need to reload updated data in to my data table when I click my button. I have been struggling. $('#manTable').DataTable().ajax.reload(); is not working. Is there any way for me to reload data. In my jsp I am actually iterating the data which is available in nested objects. After clicking any button I am actually updating the Object that is required to load DataTable. But it is not reloading the table with new data. Any help is highly appreciated.Here is my code :

    $(document).ready(function() {

        var table = $('#manTable').DataTable({
             "processing": true,
             scrollY:        '50vh',
                scrollCollapse: true,
             "columnDefs": [
                    {
                         "render": function ( data, type, full, meta ) {
                    var app = "APPROVED";
                             var rev = "REVOKED";
                             if(full.indexOf(app)!==-1 || full.indexOf(app)!==-1)
                                 return full.indexOf(app)===-1?app:rev;
                             else
                             return '<a class="btn btn-success rolloverBtn" role="button" id="appbut">Approve</a>'+"     "+
                             '<a class="btn btn-warning" role="button" id="revbut">Revoke</a>';
                         },
                      "targets": -1
                    },
                    {
                        "targets":  [0 ,1, 2, 10] ,
                        "visible": false
                    },
    
                  ]
        });
        // Handle click on "Approve" button
         $('#manTable tbody').on('click', '#appbut', function (e) {
         var rowdata = table.row( $(this).parents('tr') ).data();
         var rowIndex = table.row( this ).index();
         var jsonData = {"managerId":rowdata[0],"email":rowdata[1],"managerName":rowdata[2],
                        "userId" : rowdata[3],"userName" : rowdata[4],
                        "appId":rowdata[5],"applicationName":rowdata[6],
                        "roleId":rowdata[7],"role":rowdata[8],
                        "roleDescription" :rowdata[9],"status":rowdata[10],"action":"Approve"};
    
         var con= confirm("Are you sure you want to Approve?")
         if(con){
             console.log("inside YES BLock ::: "+JSON.stringify(jsonData))
            // Initiates an AJAX request on click
    
                    $.ajax({
                        type: "POST",
                        url: context+"approve",
                        contentType: "application/json",
                        dataType: "json",
                        timeout : 100000,
    
    
                        data: JSON.stringify(jsonData),
                            success: function(responseText){
                             // reload the data table 
                            if(responseText.code==0){
                            console.log("inside success function"+responseText.message);
                            alert(responseText.message);
                            listManagerUsers(rowdata[0]);
                        $('#manTable').DataTable().ajax.reload();
                            }else{
                                console.log("failed from server"+responseText.message);
                            alert(responseText.message)
                            }
                        },
                        error: function(e){
                            console.log("inside ERROR function")
                            alert("ERROR: ", e);
                        }
                    });
    

    // }
    }
    else
    {
    // Nothing to do here
    }
    } );

         // Handle click on "Revoke" button
         $('#manTable tbody').on('click', '#revbut', function (e) {
            var revdata = table.row( $(this).parents('tr') ).data();
    
            var jsonrevData = {"managerId":revdata[0],"email":revdata[1],"managerName":revdata[2],
                    "userId" : revdata[3],"userName" : revdata[4],
                    "appId":revdata[5],"applicationName":revdata[6],
                    "roleId":revdata[7],"role":revdata[8],
                    "roleDescription" :revdata[9],"status":revdata[10],"action":"Revoke"};
    
     var con=confirm("Are you sure you want to Revoke?")
     if(con){
         console.log("inside YES BLock ::: "+JSON.stringify(jsonrevData))
        // Initiates an AJAX request on click
    
                $.ajax({
                    type: "POST",
                    url: context+"revoke",
                    contentType: "application/json",
                    dataType: "json",
                    timeout : 100000,
                    data: JSON.stringify(jsonrevData),
                    success: function(responseText){
                         // reload the data table 
                        if(responseText.code==0){
                        console.log("inside success function"+responseText.message);
                        alert(responseText.message);
                        listManagerUsers(revdata[0]);
                        }else{
                            console.log("failed from server"+responseText.message);
                            alert(responseText.message);
                        }
                    },
                    error: function(e){
                        console.log("inside ERROR function")
                        alert("ERROR: ", e);
                    }
    
                });
    

    // }
    }
    else
    {
    // Nothing to do here
    }
    } );
    });

    function listManagerUsers(id){
    console.log("inside listManagerUsers function "+id);
    var jsonracfData = {"managerId":id};
    $.ajax({
    type: "POST",
    url: context+"listManagerUsers",
    contentType: "application/json",
    dataType: "json",
    timeout : 100000,
    data: JSON.stringify(jsonracfData),
    success: function(responseText){
    if(responseText.code==0){
    console.log("inside success function list : "+responseText.message);
    }else{
    console.log("failed from server "+responseText.message);
    alert(responseText.message);
    }
    },
    error: function(e){
    console.log("inside ERROR function")
    alert("ERROR: ", e);
    }
    });
    }

  • kthorngrenkthorngren Posts: 21,292Questions: 26Answers: 4,944

    As explained above ajax.reload() requires that you use the ajax within Datatables. However in your case using ajax is probably not what you want to do. Replace the ajax.reload() with clear() followed by rows.add() and draw() to clear the table then add all the rows and draw the updated table.

    Kevin

  • karthikchebrolukarthikchebrolu Posts: 3Questions: 0Answers: 0
    edited August 2018

    Dear Kevin
    Thanks for the reply.
    Could you please post a sample code snippet?

    Karthik

  • kthorngrenkthorngren Posts: 21,292Questions: 26Answers: 4,944
    edited August 2018

    Here is a running example.
    http://live.datatables.net/hopepicu/1/edit

    It starts with a Datatable of one row of data. Click the button to request the new data set via AJAX and update the Datatable.

    After reloading the new data the original row is not in the table.

    Kevin

  • allanallan Posts: 63,439Questions: 1Answers: 10,459 Site admin
    table
      .clear()
      .rows.add( jsonData )
      .draw();
    

    If you need a working test case showing this, priority support is available.

    Allan

  • karthikchebrolukarthikchebrolu Posts: 3Questions: 0Answers: 0

    Thanks a lot Kevin. I need to format my json object. Thanks for making me understand of this.

    Dear Allan,Thanks a lot for the tremendous support.

  • ReysantReysant Posts: 1Questions: 0Answers: 0

    Gracias por tu ejemplo, me sirvio esto:
    var table = $('#tabla').DataTable();
    table.clear();
    table.rows.add(data.data).draw();
    thanks you men :smiley:

  • BajaranglalBajaranglal Posts: 1Questions: 0Answers: 0

    This code is working
    table.clear();
    table.ajax.reload();
    table.draw();

  • isma1809isma1809 Posts: 1Questions: 0Answers: 0

    Hi, this would be for the table in mode server side?

  • intifadaintifada Posts: 1Questions: 0Answers: 0

    thanks you, @Bajaranglal
    use this code work,
    table.clear();
    table.ajax.reload();
    table.draw();

    https://datatables.net/forums/discussion/comment/169410/#Comment_169410

This discussion has been closed.