Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Session variables and set them in javascript?

In code-behind I set Session with some data.

Session["usedData"] = "sample data"; 

And the question is how can I get the Session value(in my example; "sample data") in javascript and set Session["usedData"] with a new value?

like image 692
Mehmet Ince Avatar asked Mar 20 '13 09:03

Mehmet Ince


People also ask

Can I set session variables in JavaScript?

Javascript can not directly set session values.

How do I access session variables?

To start PHP sessions, you must use the function session_start() . To set session variables, you will need to apply a global PHP $_SESSION variable . Note: The PHP session_start() function has to be the first thing in your document: all HTML tags come after.

Can I get session value in JavaScript?

Session is a Server Side object it cann't accessed directly in the Javascript as it calls in the Client Side. So, place your Session value in a hidden filed or pass the value in the Session as a parameter while calling the Script.


1 Answers

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> 
like image 200
SHEKHAR SHETE Avatar answered Oct 03 '22 12:10

SHEKHAR SHETE