Wednesday, 11 February 2015

Automatically refreshing JSON data from HTML tables using Datatables JQuery plugin

Imagine you have make a script passing data from JSON file to HTML table using DataTables JQuery plugin: this will be something like this :

    $("#hour_refundall").text('à '+ getActualHour());  
    
    var table_refund =  $('#tbrefundall').dataTable( {
        "ajax": {
            "url": "http://localhost/boot/late_payment.php?function=controle_remboursement_retard&param=json_all",
            "dataSrc": ""
        },
        "columns": [           
            { "data": "purchase_serial_number" },
            { "data": "refund_request_amount" },
            { "data": "order_detail_unit_id" },
            { "data": "purchase_creation_date" },
            { "data": "lastmod" },
        ],
        "columnDefs":[
            {
                // The `data` parameter refers to the data for the cell (defined by the
                // `data` option, which defaults to the column being worked with, in
                // this case `data: 0`.
                //"data" : "purchase_serial_number",
                "render": function ( data, type, row ) {

                    return '<a href="..?id=' + data + '"> ' + data + ' </a>';
                },
                "targets": [0]
            }

        ]
    } );

To add an automatic refresh on this table, you have just to add the following script:

    setInterval( function () {      
        table_refund.api().ajax.reload();
        $("#hour_refundall").text('à '+ getActualHour());  
        }, delay );


You will notice that I use the 'ColumnDefs' DataTables parameter to add an hyperlink to data on the table !!