3

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.

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

2

Handle xhr event. When Ajax error occurs third argument json would be null and fourth argument xhr would contain jQuery XHR object. You can get the status by accessing xhr.status property.

Also see $.fn.dataTable.ext.errMode which could be used to instruct DataTables not to show the alert.

2 Comments

Unfortunately $("#example").ajaxError(function(event, jqxhr, request, settings){ if(jqxhr.status == 500) alert("Server Side Error Occurred"); }); Does not work in 1.10.5. I can only seem to get the new handler to work.
ok. I used the xhr event and it worked perfectly. Thank You So Much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.