As part of a webapp I'm building I'll need to check if the user is logged in whenever they change page. On a normal non-ajax site this is easy because I can just place the PHP session conditional statement in the header, and the header being called on every page change will determine whether the login page is displayed or not, but seeing as the header file is only set once within an ajax application, which is on the initial load, how can I check whenever the user makes an ajax page request whether or not the session is still valid? Since I'm using pushState and popState I know I can set the condition to run whenever the URL is changed, but I don't know exactly how to code the check to run whenever this happens.
Any and all help appreciated.
Thanks.
You should return false so you can do something intelligent, like redirect the user to a log in page, or change the header as you mention in your question, instead of killing the script with die('false')
i.e.
if(!isset($_SESSION['valid_user'])) {
return false;
}
or better yet, return a json object to your script and use jquery/javascript to change the header.
$response = array();
if(!isset($_SESSION['valid_user'])) {
$response['logged_in'] = false;
} else {
$response['logged_in'] = true;
}
// return to jquery for handling
return json_encode($response);
either way, you say you're building a web application, so you might want to try handling the event instead of killing the program.
Create a php page that checks the session and returns true or false.
So if the user is not logged in, whenever you do an ajax request and the session doesn't have the user information, only the string false is returned which you can use to check in the ajax callback to display the right information
E.G
if(!isset($_SESSION['user'])) die('false');
Then in your ajax callback, you can check if the response is false, or handle the data another way E.G
$.ajax({"url" : url, "success" : function(response){
if(response == 'false')
{
// display a login screen or redirect the user to a login page
// E.G showLogin() or document.location = '/login.php';
} else {
// to something else with the response if the user is logged in
}
});