[jquery] Get Current Session Value in JavaScript?

I have a scenario where I open my web application in a browser but in two separate tabs.

In one tab I signed out from the application and as a result the all session values becomes null. While in the other tab I clicked on an anchor tag in the webapplication. In the anchor tag's jquery-on click event I have checked the session value. Here I am supposed to get the session as null(since I logged out the application from the other tab), but I am getting session value as logged in user(probably because no page refresh occurs).

My idea is to check the session on jQuery and if the session is null make the application logout,otherwise show a popup page..

Here's my code for getting the session value

$(".a".click(function(){
   var session=var data = '@Session["UserName"]';
   if(session!=null){
    //Show popup
   }
   else{
    //Show loginpage
   }

}))

How can I get the current session value in jQuery?

This question is related to jquery asp.net session

The answer is


The session is a server side thing, you cannot access it using jQuery. You can write an Http handler (that will share the sessionid if any) and return the value from there using $.ajax.


Another approach is in your chtml

<input type="hidden" id="hdnSession" data-value="@Request.RequestContext.HttpContext.Session['someKey']" />

  and the script is

var sessionValue= $("#hdnSession").data('value');

or you may access directly by

 jQuery(document).ready(function ($) {
        var value = '@Request.RequestContext.HttpContext.Session["someKey"]';
    }); 

this is how i used ->

<body  onkeypress='myFunction(event)'>

<input type='hidden' id='homepage' value='$_SESSION[homepage]'>


<script>
    function myFunction(event){var x = event.which;if(x == 13){var homepage 
    =document.getElementById('homepage').value;
    window.location.href=homepage;}else{     
    document.getElementById("h1").innerHTML = "<h1> Press <i> ENTER </i> to go back... </h1>";}}
</script>
</body>

I am using C# mvc Application. I have created a session in the Controller class like this

string description = accessDB.LookupSomeString(key, ImpDate);
this.Session["description"] = description;    

in the View, We access the session value and store it in a variable, like this (this is within an $.ajax, but I think it should work within any jquery)

var Sessiondescription = '@Session["description"]';
alert(Sessiondescription);

i tested this method and it worked for me. hope its useful.

assuming that you have a file named index.php
and when the user logs in, you store the username in a php session; ex. $_SESSION['username'];

you can do something like this in you index.php file

<script type='text/javascript'>
  var userName = "<?php echo $_SESSION['username'] ?>"; //dont forget to place the PHP code block inside the quotation 
</script>

now you can access the variable userId in another script block placed in the index.php file, or even in a .js file linked to the index.php

ex. in the index.js file

$(document).ready(function(){
    alert(userId);   
})

it could be very useful, since it enables us to use the username and other user data stoerd as cookies in ajax queries, for updating database tables and such.

if you dont want to use a javascript variable to contain the info, you can use an input with "type='hidden';

ex. in your index.php file, write:

<?php echo "<input type='hidden' id='username' value='".$_SESSION['username']."'/>";
?>

however, this way the user can see the hidden input if they ask the browser to show the source code of the page. in the source view, the hidden input is visible with its content. you may find that undesireble.


Take hidden field with id or class and value with session and get it in javascript.

Javascript var session = $('#session').val(); //get by jQuery


would be a lot easier to use Razor code in your page.

in my example, i needed to set a hidden field with a session variable.

$('#clearFormButton').click(function(){
    ResetForm();
    $('#hiddenJobId').val(@Session["jobid"]);
});

that easy. remember, you need to preface the Session with a @ sign for razor syntax.


The way i resolved was, i have written a function in controller and accessed it via ajax on jquery click event

First of all i want to thank @Stefano Altieri for giving me an idea of how to implement the above scenario,you are absolutely right we cannot access current session value from clientside when the session expires.

Also i would like to say that proper reading of question will help us to answer the question carefully.


_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function(){_x000D_
_x000D_
   var userId=<%: Session["userId"] %>;_x000D_
    alert(userId);   _x000D_
})   _x000D_
</script>
_x000D_
**Get the current session value in jQuery**
_x000D_
_x000D_
_x000D_


try like this

var username= "<%= Session["UserName"]%>";

Accessing & Assigning the Session Variable using Javascript:

Assigning the ASP.NET Session Variable using Javascript:

 <script type="text/javascript">
function SetUserName()
{
    var userName = "Shekhar Shete";
    '<%Session["UserName"] = "' + userName + '"; %>';
     alert('<%=Session["UserName"] %>');
}
</script>

Accessing ASP.NET Session variable using Javascript:

<script type="text/javascript">
    function GetUserName()
    {

        var username = '<%= Session["UserName"] %>';
        alert(username );
    }
</script>

Already Answered here


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to session

What is the best way to manage a user's session in React? Spring Boot Java Config Set Session Timeout PHP Unset Session Variable How to kill all active and inactive oracle sessions for user Difference between request.getSession() and request.getSession(true) PHP - Session destroy after closing browser Get Current Session Value in JavaScript? Invalidating JSON Web Tokens How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session How can I get session id in php and show it?