Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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

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

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.

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.

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

try like this

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

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

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

<script type="text/javascript">
$(document).ready(function(){

   var userId=<%: Session["userId"] %>;
    alert(userId);   
})   
</script>
**Get the current session value in jQuery**

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>

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top