Just check the response code when making ajax requests. If you get an error, send the user to the login page.
$.get("somepage.php").always(function (response) {
// check response code
if (response.status !== 200) {
// did not succeed. redirect to loging page
window.location.replace("login_page.php");
return;
}
// response is ok
});
You can also use the location
header from the response to figure out where to redirect.
$.get("somepage.php").always(function (response) {
// check if it's a redirect (300 code)
if (Math.round(response.status / 100.0) * 100 === 300) {
// redirect to the location header
window.location.href = response.getResponseHeader("location");
return;
}
});
You could do something like this to check on an interval
var checkSession = function () {
var isRedirect = function (code) {
return Math.round(code / 100.0) * 100 === 300;
};
$.ajax({
type : "HEAD", // https://ochronus.com/http-head-request-good-uses/
async : true,
url : "somepage.php",
success: function (_, _, response) {
if (isRedirect(response.code)) {
window.location.href = response.getResponseHeader("location");
}
}
});
};
$(function () {
// check the session every 30 seconds
setInterval(checkSession, 30*1000);
});