Created
June 22, 2015 06:53
-
-
Save alxsimo/d59b486d2a440854e3e2 to your computer and use it in GitHub Desktop.
[Ajax/jQuery] Handle sessions in client side with ajax requests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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