I have searched many, many topics on the Net discussing about session variables and how to get them from Javacript through Ajax. However, though I have been able to do so, this
It's an idea, but you can work on/from it;
actionURL is a php file where you can check if the user is logged in with a valid session.
ajaxSession function returns true or false if the user is logged.
Then you can call this function every X seconds/minutes to control if the session still going.
window.setInterval(function(){
// call your function here
if(ajaxSession(actionUrl)){
//return true, user logged, append/show protected divs.
}else{
//return false, remove/hide protected divs and ask user to log.
}
}, 5000); //every 5 seconds.
ajaxSession function:
function ajaxSession(actionUrl) {
var sessionOK= false;
$.ajax({
async: false,
url: actionUrl,
success: function(msg) {
// check the return call from the php file.
if(msg== 'OK'){
sessionOK = true;
}else{
sessionOk = false;
}
}});
return sessionOK;
}
EDIT
I will add an example code for the actionUrl, that will return if the session is isset or not to the ajaxSession function:
<?php
session_start();
// $_SESSION['reg'] is true when the user is logged in.
if($_SESSION['reg'] == true){
echo 'OK';
}else{
echo 'NO';
}
?>
Remember to check in the ajaxSession function the result of the Ajax call. If it's Ok, then sessionOk = true, if not, sessionOk = false.