Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the ajax call for jQuery DataTable has returned data

I am trying to load the jQuery DataTable from an AJAX call as in the code below. However I need to know if there is a callback for the DataTable to check if the AJAX call returned successfully or failed before the table is loaded.

$(function() {
  $('#data-table').DataTable({
    destroy: true,
    responsive: true,
    serverSide: false,
    autoWidth: false,
    paging: true,
    filter: true,
    searching: true,
    stateSave: true,
    scrollX: true,
    lengthMenu: [5, 10, 25, 50, 75, 100],
    ajax: {
      url: 'https://jsonplaceholder.typicode.com/todos',
      type: 'GET',
      dataSrc: ''
    },
    columns: [{
      title: 'Zone',
      data: 'LastKnownZone',
    }, {
      title: 'Hiérarchie Map',
      data: 'MapInfo.mapHierarchyString',
    }, {
      title: 'Addresse MAC',
      data: 'macAddress',
    }],
    initComplete: function(json) {
      let returned_data = json;
      //..Do something with data returned
    }
  });
});

Appreciate any help.

like image 970
Xris Avatar asked Oct 16 '25 06:10

Xris


2 Answers

Just adding something to @Fawaz Ibrahim's answer, it's also better to add error option in Ajax call in order to check if you face any error or problem , because in case of error, dataSrc callback won't run, so you won't have any successful returned data.

ajax: {
  ...
  dataSrc: function ( receivedData ) {
    console.log('The data has arrived'); // Here you can know that the data has been received
    return receivedData;
  },  
 error: function (xhr, error, thrown) {
     console.log('here you can track the error');
  }
}
like image 127
Razi Avatar answered Oct 18 '25 21:10

Razi


As it is mentioned on their official site:

For completeness of our Ajax loading discussion, it is worth stating that at this time DataTables unfortunately does not support configuration via Ajax. This is something that will be reviewed in future

But you can use the idea of datasrc, like this:

$(function() {
  $('#data-table').DataTable({
    ...
    ajax: {
      ...
      dataSrc: function ( receivedData ) {
        console.log('The data has arrived'); // Here you can know that the data has been received
        return receivedData;
      }
    },
    ...
  });
});
like image 32
Fawaz Ibrahim Avatar answered Oct 18 '25 21:10

Fawaz Ibrahim