views:

90

answers:

6

For convenient notification purposes, not secure information purposes:

I have javascript polling for new information while logged in. I want it to stop while logged out. What is the best way to let javascript know about the logged-in/logged out status?

Run a javascript function on login, and one on logout (which might get skipped if they navigate away and come back directly)? Run a poll periodically to check for access to secure (logged-in-only) information and skip further polls if that access isn't available? Another option that I haven't found yet?

I'm running php server-side, if matters.

+2  A: 

Set a cookie on login/logout actions: e.g. logged=1 :)

o_O Tync
+2  A: 

Have javascript poll as normal, and when it tries to poll while logged out, return an error.

cobbal
+1  A: 

You could just set a Javascript boolean at page load time: true if the user's logged in, and false if they're not.

Kaleb Brasee
It's not what the author tries to do, as I can see. It is required to stop javascript polling without reloading the page if the user has been logged out (i.e., session expired or logged out in a different tab).
Igor Zinov'yev
+4  A: 

The Cookie approach should work. The other thing you can do is create a JSON page that returns true or false if the user is logged in. Then check that before your other code, if it's logged in do what you do, if not do something else, perhaps redirect to Login page?

In jQuery it goes something like this:

$.getJSON("/login/is_logged", function(json) {
    if(!json.User.logged) {
     window.location = '/login/form/';
    }
});

The JSON page (url /login/is_logged) returns this:

{"User":{"logged":true}}

Here's the link to $.getJSON.

Eduardo Romero
A: 

Ok, here is what I decided to do:

  • Keep a boolean that corresponds to
  • logged in/logged out state (1 or 0).
  • Login toggles 1.
  • Logout toggles 0.
  • If the existing polling checks the api and gets false return values because a logout has occurred, it will toggle the boolean to 0 as well (after either 1 or two false information checks).
  • Once the boolean is 0, no further polling will occur until a login event toggles it back to 1.
Tchalvak
+1  A: 

You can add a class="loggedin" or id="loggedin" to the <body> or <html> tags, and read these with the DOM / jQuery functions.

The class of the HTML tag can be read with: document.documentElement.className.

Since your server-side PHP already knows if the user is logged in, or not, it could add the proper "logged in" <script> code in the page too.

vdboor