Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

datatables: how to catch error when using custom ajax function?

While using datatables I need to use a custom ajax-function.

The canonical example as found here is as follows:

$('#example').dataTable( {
  "ajax": function (data, callback, settings) {
    //some async processing happening here
    //In the end call the callback. 
    //However, this callback only accepts a success state
    // instead of the usual cb(err, resp) signature. 
    //This raises the question how to let Datatables know there's an error.
    const err = new Error("some contrived error");


    //This doesn't work, datatables doesn't signal an actual error
    //which can be surfaced to the client. Instead it complains
    //the response doesn't have a 'data'-object which it needs
    //to correctly create the table. In other words, datatables
    //thinks that the passed err-object is an actual correct response. 

    //Question: so how to actually let datatables know there's an actual error?
    callback(err);
  }
} );

However, I don't see a way to let datatables know that an ajax-error occurred.

How to do this?

like image 324
Geert-Jan Avatar asked Jun 27 '17 09:06

Geert-Jan


1 Answers

After trying a few different methods, I think your best bet will be to call the callback function with your data on a success and call callback with empty data on a failure. If there is an error, you can set the text of the .dataTables_empty row to the text of your error message, so it will display in the table. Here's how it would work, and what the code would look like:

Important Note - Make sure to set the .dataTables_empty text after you call the callback, because the callback will set it back (which is actually nice because then you don't have to reset it yourself on each data load)

$('#example').dataTable( {
  "columns": [
    {"data": "col1"},
    {"data": "col2"},
    {"data": "col3"},
  ],
  "ajax": function (data, callback, settings) {
    // simulate ajax call with successful data retrieval
    var myAjaxCall = new Promise(function (resolve, reject) {
      $(".dataTables_empty").text("Loading...");
      setTimeout(function () {
        // `callback()` expects an object with a data property whose value is either 
        // an array of arrays or an array of objects. Must be in this format
        // or you get errors.
        var ajaxData = {"data": [
          {"col1": "1.1", "col2": "1.2", "col3": "1.3"},
          {"col1": "2.1", "col2": "2.2", "col3": "2.3"},
          {"col1": "3.1", "col2": "3.2", "col3": "3.3"}
        ]};
        resolve(ajaxData);
      }, 1500);
    });
    
    myAjaxCall.then(function resolveCallback(data) {
      // render data returned from ajax call
      callback(data);
    }, function rejectCallback(err) {
      callback({data: []});
      $(".dataTables_empty").text(err); 
    });
  }
});

$('#example2').dataTable( {
  "columns": [
    {"data": "col1"},
    {"data": "col2"},
    {"data": "col3"},
  ],
  "ajax": function (data, callback, settings) {
    // simulate unsuccessful ajax call
    var myAjaxCall2 = new Promise(function (resolve, reject) {
      $(".dataTables_empty").text("Loading...");
      setTimeout(function () {
        // reject promise with error message
        reject("Something went terribly wrong!");
      }, 1500);
    });
    
    myAjaxCall2.then(function resolveCallback(data) {
      callback(data);
    }, function rejectCallback(err) {
      // render table with no results
      callback({data: []});
      // set dataTables empty message text to error message
      $(".dataTables_empty").text(err); 
    });
  }
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" />
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<h1>Success</h1>
<table id="example">
  <thead>
    <tr>
      <th>Col 1</th>
      <th>Col 2</th>
      <th>Col 3</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
<h1>Error</h1>
<table id="example2">
  <thead>
    <tr>
      <th>Col 1</th>
      <th>Col 2</th>
      <th>Col 3</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
like image 104
mhodges Avatar answered Sep 20 '22 07:09

mhodges