Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Error Message after Datatables ajax exception

I am displaying a table of data using datatables 1.10.12. The user can specify input parameters that cause an error on the server. An appropriate error message should be displayed to the user so they can modify their setup, however the only error options seem to be:

  1. SHow the following generic error in an alert: "DataTables warning: table id=trackingTable - Ajax error. For more information about this error, please see http://datatables.net/tn/7"
  2. Show the generic error in the browser console
  3. Modify the server to return no rows, that is fail silently.

Does anyone know how to show a custom error after a datatables ajax request fails?

The following code sample is taken from the datatables documentation. Datatables handles the ajax call and handles success and error.

$(document).ready(function() {
    $('#example').DataTable( {
        "ajax": '../ajax/data/arrays.txt'
    } );
} );

A 4th option I could add to the list would be to modify the datatables source code to handle the an error response myself. Which I'm not that keen on.

This question was asked in 2015 however it did not get an answer. See: display server side exception

like image 571
nap Avatar asked Aug 11 '16 02:08

nap


People also ask

What causes an Ajax error?

Many pages send AJAX requests to a server. Because this relies on the cooperation of the server and the network between the client and the server, you can expect these AJAX errors: Your JavaScript program receives an error response instead of data; Your program has to wait too long for the response.

What is a DataTables warning?

DataTables warns about the use of them by default, as the majority of the time they are not intended for display - for example, rather than showing null in the table, you might want to show Not yet set, or simply an empty string (empty cell). For this, DataTables has a columns. defaultContent option.

What is an Ajax warning?

Meaning. This occurs when jQuery falls into its error callback handler (this callback built into DataTables), which will typically occur when the server responds with anything other than a 2xx HTTP status code.


1 Answers

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.

like image 120
Nick Pyett Avatar answered Sep 17 '22 14:09

Nick Pyett