Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datatables 1.10.5 ajax error handler - Getting access to the http status code

I'm using Datatables 1.10.5 and I have the ajax error handler defined. I need to gain access to the actual http status code when the error fires so I can see if my user's session time has expired (HTTP 401) vs if there's something wrong on the backend such as an HTTP 500 error. Right now the techNote is always 7.

How can I get that elusive HTTP status code from the ajax transaction? I tried below, but it does not fire.

$("#example").ajaxError(function(event, jqxhr, request, settings){
    alert("Failure HTTP Code:"+jqxhr.status);    
});

and

$.fn.dataTable.ext.errMode = 'throw';
$('#example').on('error.dt', function(e, settings, techNote, message) {
   console.log( 'An error has been reported by DataTables: ', message);
});

Does not have the information I need, or at least that I cannot find it in any of the passed variables.

like image 928
user3670534 Avatar asked Jul 01 '26 09:07

user3670534


1 Answers

I've been able to get access to the status code without overriding global jQuery ajaxError by overriding the more specific to DataTables $.fn.dataTable.ext.errMode with a function:

    $.fn.dataTable.ext.errMode = function (settings, tn, msg) {
      if (settings && settings.jqXHR && settings.jqXHR.status == 401) {
          window.location = window.location.origin + '/login';
          return
      }
      alert(msg) // Alert for all other error types; default DataTables behavior
    };

This example shows a redirect to login on 401 status code, however, you could do the same with any other status code.

Last note is you might want to leverage the DataTables statusCode option for status code specific handling but you'll still need to override $.fn.dataTable.ext.errMode if you want to bypass default error handling since it executes before anything you define in statusCode

like image 108
quetzaluz Avatar answered Jul 04 '26 15:07

quetzaluz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!