0

I have an app with frontend in javascript (using AngularJS and jQuery) and backend in java. The app has many pages (ng-view).

I need to know whether the session in the backend is currently active or invalidated. Based on that I need to decide whether to show Logout button on the page or not.

Although I have learnt that the session is maintained in the browser using session cookies, from this and this, I concluded that we have to manually set the variable values in the cookie object that we create in javascript.

Is there any way to get the session cookie that is used to communicate with server? By getting that cookie, we can perhaps see whether the session is currently active or not.

Please let me know if my interpratation is wrong.

Community
  • 1
  • 1
vishalaksh
  • 2,054
  • 5
  • 27
  • 45
  • That's not the way to go. You won't have access to the server's records on session existence. Anyone might create a local cookie with a session ID in it. – Joost Aug 25 '15 at 07:34
  • Why don't you have your view page output conditionally on whether or not there's a session? The cookie is not reliable because the server may have its own session timeout. – raduation Aug 25 '15 at 07:34
  • @raduation you mean to say that I should first query from the server for the existence of the session from each page and then decide to display logout button based on it? – vishalaksh Aug 25 '15 at 07:38
  • Yes, you should check on the server side whether there is an active session and do an if statement to show or not show the logout button. – raduation Aug 25 '15 at 07:39

4 Answers4

1

You can't check the session expire or not in java script using Session because if you write code like this:

if (isset($_SESSION["PHPSESSID"])) {}

that write on document it working properly but can not change value call of the javascript. if you reload a page than it update session value.

Pradip Talaviya
  • 399
  • 2
  • 8
  • 22
0

Generally you don't have access to session cookies from JavaScript. The simplest way is just to make an ajax request to the server to check if you have an authenticated session. Alternatively you can set a custom cookie with session info.

Andreas Møller
  • 839
  • 5
  • 9
0

use ajax code PHP (session.php)

<?php
session_start();
if (isset($_SESSION['username'])) {
    echo 'success';
}

jquery:

$.ajax({
    url: 'path-to/session.php',
    type: 'POST',
    success: function(result) {
        if (result == 'success'){
            //...
        }else{
            //...
        }
    }
});
Bassem Shahin
  • 656
  • 7
  • 13
-1

Actually there is a way you can use to check session via javascript, here is the code

$.get('path/to/session_check.php', function(data) {
 if( data == "Expired" ) {
     alert("Session expired");
 } else if (data == "Active" ) {
     alert("Session active");
 }
});
Engr Atiq
  • 163
  • 2
  • 16