Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set an error handler for jquery datatables ajax call

I'm trying to have a custom error handler when something goes wrong (i.e. the server does not respond) on the ajax call for loading new data into my datatable.

$table.DataTable().ajax.url(ajaxURL).load();

By default it shows an alert and I can change that to throw a javascript error with the following setting:

$.fn.dataTable.ext.errMode = 'throw';

But with this, I just have an error logged to the console and I'm not sure how to catch that thrown error so I still can't provide my own error handler.

There is also an error event listed in the documentation, but that doesn't seem to get triggered, so the following never alerts.

$table.on( 'error', function () { alert( 'error' );} );

Everything else I've found so far is for the legacy code, such as setting the fnServerData, which I would like to avoid getting into.

Is there a method to set the ajax error callback in the 1.10 API?

like image 894
aaron Avatar asked Jan 20 '15 16:01

aaron


3 Answers

New error event handling has been added in Datatables v1.10.5 (released 10th February 2015).

$.fn.dataTable.ext.errMode = function ( settings, helpPage, message ) { 
    console.log(message);
};

See docs here:
https://datatables.net/reference/event/error
https://cdn.datatables.net/1.10.5/

like image 112
s0ndeb0k Avatar answered Oct 08 '22 10:10

s0ndeb0k


Use the Ajax error function to log errors:

$('#table').DataTable({
    ajax: {
        dataType: "JSON",  
        type: "POST",
        url: url,
        data: [],
        async: true,
        error: function (xhr, error, code) {
            console.log(xhr, code);
        }
    },
});
like image 23
Khaan Avatar answered Oct 08 '22 12:10

Khaan


Use the event as a custom error handler:

$(document).ready(function () {
    $('#myTable').on('error.dt', function (e, settings, techNote, message) {
        console.log('An error has been reported by DataTables: ', message);
    }).DataTable({
        "displayLength": 15,
        "ajax": {
          ....
like image 3
J.C. Gras Avatar answered Oct 08 '22 11:10

J.C. Gras