Reputation: 63
I've been wanting to create a JavaScript function that changes the PHP session timeout for both logged-in and not-logged-in user.
I've added the session timeout to header.php. This is because when users are logged in, users are able to access whole website. However, some pages are accessible to both logged-in and not-logged-in users.
I'm not sure how to make the JavaScript in if else
statement such it will differentiate guest session id
or may be the success of the Ajax to accommodate the true or false return from the PHP. I'm unsure how it should be done.
As of now, my website will show the pop out for both logged-in and not-logged-in users as I've added the session timeout and the Ajax in header.php
Searched everywhere, but could not find any leads at all. Please help me. Thanks! Here's my code.
ajax.js
window.onload = init;
var interval;
function init() {
interval = setInterval(trackLogin, 1000);
}
function trackLogin() {
var xmlReq = false;
try {
xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlReq = false;
}
}
if (!xmlReq && typeof XMLHttpRequest != 'undefined') {
xmlReq = new XMLHttpRequest();
}
xmlReq.open('get', 'check.php', true);
xmlReq.setRequestHeader("Connection", "close");
xmlReq.send(null);
xmlReq.onreadystatechange = function() {
if (xmlReq.readyState == 4 && xmlReq.status == 200) {
if (xmlReq.responseText == 1) {
clearInterval(interval);
alert('You have been logged out. You will now be redirected to home page.');
document.location.href = "index.php";
}
}
}
}
Upvotes: 0
Views: 374
Reputation: 50787
It looks to me as if your server returns 1
which is what the line xmlReq.responseText == 1
is evaluating. Instead just return a JSON object and then parse that response and look for the result.
In PHP, return a JSON encoded array as opposed to return true
return json_encode(array(
'role' => $_SESSION['role'], //assuming something like guest/logged-in
'user_id' => $_SESSION['user_id']
));
Then parse your response text like such in order to make a comparison:
var obj = xmlReq.responseText;
var jsonObj = JSON.parse(obj);
//now we can make a comparison against our keys 'role' and 'user_id'
if(jsonObj['role'] == 'guest'){
//guest role, do something here
} else if (jsonObj['role'] == 'logged-in') {
//do something else for logged in users
}
Good luck.
Upvotes: 1