How to make table wait for json ready?

How to make table wait for json ready?

ketnaketna Posts: 8Questions: 4Answers: 0

I use one source data to feed couple views (table, calendar, gantt etc.). I need to make only one ajax call (otherwise it is very slow).
I have a problem with making datable to wait until variable with json is ready. I would be grateful for any help.

let apiUrl = "abc.php"
let xdata = null
async function getJson() {
const response = await fetch(apiUrl);
const data = await response.json();
return data;
}
getJson().then((data) => {
xdata=data
});

xTable = $('#xtable').DataTable({
"ajax": async function (d, callback, s) {
data: await xdata;
}
});

Answers

  • kthorngrenkthorngren Posts: 21,327Questions: 26Answers: 4,949

    Try doing something like this which should initialize Datatables after the JSON response:

      $.getJSON( apiUrl, function( data ){
        $('#xtable').DataTable({
            data: data,
        });
      });
    

    Kevin

  • ketnaketna Posts: 8Questions: 4Answers: 0

    Thank you for suggestion, however this solution will make again the same query so it will not help.

  • kthorngrenkthorngren Posts: 21,327Questions: 26Answers: 4,949

    however this solution will make again the same query so it will not help.

    Please provide more details of what this means so we can suggest a more appropriate solution.

    Maybe one of these ideas will work:

    1. Use the combination of ajax to fetch the data then use -ajax.reload() when you want to refresh the table.
    2. Init Datatbles without any data then use clear() to clear the table followed by rows.add() to add the new data, something like this:
    var table = $('#xtable').DataTable();
    $.getJSON( apiUrl, function( data ){
      table.clear();
      table.rows.add( data ).draw();
    });
    

    Kevin

Sign In or Register to comment.