简体   繁体   中英

How to check whether session exists from javascript?

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.

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.

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.

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{
            //...
        }
    }
});

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");
 }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM