Custom Error Message after Datatables ajax exception Custom Error Message after Datatables ajax exception ajax ajax

Custom Error Message after Datatables ajax exception


If you pass an object to the ajax property you can override the jQuery.ajax() error method:

$(document).ready(function () {    $('#example').DataTable({        ajax: {            url: '../ajax/data/arrays.txt',            error: function (jqXHR, textStatus, errorThrown) {                // Do something here            }        }    });});

https://datatables.net/reference/option/ajax#object

This will stop the standard error message in the alert box.

Please note, it is not recommended to override the success method of jQuery.ajax() as it is used by DataTables.


You can implement your own custom error message globally like the example below.

$(document).ready(function() {        $.fn.dataTable.ext.errMode = () => alert('Error while loading the table data. Please refresh');        $('#example').DataTable( {            "ajax": '../ajax/data/arrays.txt'        });    });


Answering just in case someone is still looking for a solution.

In my case, I did the following

  1. At server side set DataTablesOutput object.setError("ErrorMsg")
  2. In my js method $.fn.dataTable.ext.errMode = 'none'; to avoid the error popup.
  3. Created an error div in my page to display the custom error message
  4. Added the below to my js method to handle error

    $('#myDataTable')        .on('error.dt',            function(e, settings, techNote, message) {//Logic to set the div innertext              }