Skip to content

Instantly share code, notes, and snippets.

@yajra
Last active June 30, 2022 20:34
Show Gist options
  • Save yajra/ddb9a28dcc120d1a5d2c to your computer and use it in GitHub Desktop.
Save yajra/ddb9a28dcc120d1a5d2c to your computer and use it in GitHub Desktop.
Laravel 5.x solution to redirect AJAX expired session to login page and disable DataTables error prompt
/**
* Requirements:
* - jQuery (http://jquery.com/)
* - DataTables (http://datatables.net/)
* - BootboxJS (http://bootboxjs.com/)
* ---------------------------------------------------------------------------
* Credits to https://gist.github.com/flackend/9517696
* ---------------------------------------------------------------------------
* This monitors all AJAX calls that have an error response. If a user's
* session has expired, then the system will return a 401 status,
* "Unauthorized", which will trigger this listener and so prompt the user if
* they'd like to be redirected to the login page.
*/
$(document).ajaxError(function(event, jqxhr, settings, exception) {
if (exception == 'Unauthorized') {
// Prompt user if they'd like to be redirected to the login page
bootbox.confirm("Your session has expired. Would you like to be redirected to the login page?", function(result) {
if (result) {
window.location = '/login';
}
});
}
});
// disable datatables error prompt
$.fn.dataTable.ext.errMode = 'none';
@sebastianvirlan
Copy link

sebastianvirlan commented Feb 25, 2018

I used this strategy for shutting up the Unauthorised error and just redirect to login page but alert any other error message.

            $.fn.dataTable.ext.errMode = 'none';
            LaravelDataTables["dataTableBuilder"].on( 'error.dt', function ( e, settings, techNote, message ) {
                
                settings.jqXHR.statusText === 'Unauthorized' ? window.location = '/login' : alert(message);
                console.log(message);
                return true;
                
            });

@bjmercado
Copy link

@yajra salamat ulit kabayan!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment