Skip to content

Instantly share code, notes, and snippets.

@alxsimo
Created June 22, 2015 06:53
Show Gist options
  • Save alxsimo/d59b486d2a440854e3e2 to your computer and use it in GitHub Desktop.
Save alxsimo/d59b486d2a440854e3e2 to your computer and use it in GitHub Desktop.
[Ajax/jQuery] Handle sessions in client side with ajax requests
/*
Handles session expired in AJAX requests
*/
$(document).ajaxError(function(e, jqXHR, ajaxSettings, thrownError) {
// if 403 - check if user still has active session - if not redirect to login page
if(jqXHR.status == '403' || jqXHR.status == '500'){
$.get('/users/check_session',function(data){
// inactive session so redirect to login page
if(data != '1'){
window.location = '/users/login/expired';
}
// likely does not have perimissions
else if(jqXHR.status == '403'){
notification('error','Access Denied (Permissions)',ajaxSettings.url);
}
else{
notification('error','Internal Error Encountered',ajaxSettings.url);
}
})
}
else{
notification('error','Error Encountered',thrownError+' (HTTP CODE: '+jqXHR.status+')
'+ajaxSettings.url);
console.log(e,'event');
console.log(jqXHR,'xhr response');
console.log(ajaxSettings,'$.ajax settings');
}
});
// Dummy test in onSuccess
$(document).ajaxSuccess(function(evt, request, settings){
if (request.responseText.indexOf('UserLoginForm') != -1)
location.href="/login";
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment