0
votes

I inherited a Laravel application that is using Yajra DataTables to display grid content in a page.

If Laravel's session expires, the DataTable will throw the following alert:

DataTables warning: table id=dataTableBuilder - Ajax error. For more information about this error, please see http://datatables.net/tn/7

Viewing the Network tab in Chrome shows me that the AJAX response for the DataTable was a 401 Unauthorized. This is all expected behavior, but instead of displaying an arbitrary error to the user, I'd like to send the user to the login page with a message that says "your session timed out, please log in again." or something.

I can't figure out how to do that.

Traditional DataTables integrations allow me to pass an error handler to the AJAX response (i.e. {ajax: { error: function () {...} }}), but there doesn't seem to be a way to do that with Laravel DataTables.

Laravel DataTables has an html() method that I can override like so:

public function html() {
    return $this->builder()
           ->ajax([
             error => ''
           ]);
}

But the ajax method on the builder doesn't allow me to pass a JavaScript handler to the error property.

Is there anyway to accomplish the force login when sessions time out?

2
Are you sure you can't do something like 'error' => 'window.handleDTAjaxError()' ?Ohgodwhy
@Ohgodwhy Yeah, I tried doing that and instead of rendering it as a JavaScript method call, it simply treats it as a string.Jeff Jenkins

2 Answers

1
votes

Given the comment chain above, my suggestion would be to put a unique string in the error response, like:

code: 401

Then, use the global $.ajaxError to catch errors and do something different based on the response text:

$( document ).ajaxError(function( event, jqxhr, settings, thrownError ) {
    if (typeof settings === "string" && settings.indexOf('401') > -1) {
        //you can probably do something here
    }
});

You could probably even do this in a more efficient way as the 401 response type should be observable in one of the 4 properties (can't remember which)

0
votes

An option more specific to DataTables that would not necessitate a global override is to use a function for $.fn.dataTable.ext.errMode

    $.fn.dataTable.ext.errMode = function (settings, tn, msg) {
      if (settings && settings.jqXHR && settings.jqXHR.status == 401) {
         // Handling for 401 specifically
      }
      // Handling for all other errors, this implements the DataTables default 
      // behavior of throwing an alert
      alert(msg)
    };