How to access Session variables and set them in javascript?

Javascript.NetSession

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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>

Solution 2 - Javascript

You can't access Session directly in JavaScript.

You can make a hidden field and pass it to your page and then use JavaScript to retrieve the object via document.getElementById

Solution 3 - Javascript

Javascript can not directly set session values. For setting session values from javascript I do ajax call as follows.

Check Online

At ASPx file or html,

 <script type="text/javascript">
 $(function(){
   //Getting values from session and saving in javascript variable.
   // But this will be executed only at document.ready.
   var firstName = '<%= Session["FirstName"] ?? "" %>';
   var lastName = '<%= Session["LastName"] ?? "" %>';
   
   $("#FirstName").val(firstName);
   $("#LastName").val(lastName);
   
   $('Button').click(function(){
     //Posting values to save in session
     $.post(document.URL+'?mode=ajax', 
	 {'FirstName':$("#FirstName").val(),
     'LastName':$("#LastName").val()
     } );
   });
   
 });

At Server side,

protected void Page_Load(object sender, EventArgs e)
 {
	  if(Request.QueryString["mode"] != null && Request.QueryString["mode"] == "ajax")
      {
		//Saving the variables in session. Variables are posted by ajax.
        Session["FirstName"] = Request.Form["FirstName"] ?? "";
        Session["LastName"] = Request.Form["LastName"] ?? "";
      }
 }

For getting session values, as said by Shekhar and Rajeev

var firstName = '<%= Session["FirstName"] ?? "" %>';

Hope this helps.

Solution 4 - Javascript

Try This

var sessionValue = '<%=Session["usedData"]%>'

Solution 5 - Javascript

Assuming you mean "client side JavaScript" - then you can't, at least not directly.

The session data is stored on the server, so client side code can't see it without communicating with the server.

To access it you must make an HTTP request and have a server side program modify / read & return the data.

Solution 6 - Javascript

Assign value to a hidden field in the code-behind file. Access this value in your javascript like a normal HTML control.

Solution 7 - Javascript

You can't set session side session variables from Javascript. If you want to do this you need to create an AJAX POST to update this on the server though if the selection of a car is a major event it might just be easier to POST this.

Solution 8 - Javascript

first create a method in code behind to set session:

 [System.Web.Services.WebMethod]
 public static void SetSession(int id)
 {
     Page objp = new Page();
     objp.Session["IdBalanceSheet"] = id;
 }

then call it from client side:

function ChangeSession(values) {
     PageMethods.SetSession(values);
     }

you should set EnablePageMethods to true:

<asp:ScriptManager EnablePageMethods="true" ID="MainSM" runat="server" ScriptMode="Release" LoadScriptsBeforeUI="true"></asp:ScriptManager>

Solution 9 - Javascript

If you want read Session value in javascript.This code help for you.

<script type='text/javascript'> var userID='@Session["userID"]'; </script>

Solution 10 - Javascript

I was looking for solution to this problem, until i found a very simple solution for accessing the session variables, assuming you use a .php file on server side. Hope it answers part of the question :

access session value

<script type="text/javascript">        
    var value = <?php echo $_SESSION['key']; ?>;
    console.log(value);
</script>

Edit : better example below, which you can try on phpfiddle.org, at the "codespace" tab

<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <?php
    $_SESSION['key'] = 10;
    $i = $_SESSION['key'];
  ?>
 </head>
 <body>
  <p id="affichage">hello</p>

  <script type="text/javascript">
   	var value =  <?php echo $i; ?>;
	$("#affichage").html(value);   
  </script>

 </body>
</html>

set session value

pass it a variable of whatever, you may want to. eg,

$you = 13;
$_SESSION['user_id'] = $you;

This should work, tho' not tested it.

Solution 11 - Javascript

You could also set the variable in a property and call it from js:

On the Server side :

Protected ReadOnly Property wasFieldEditedStatus() As Boolean
    Get
        Return If((wasFieldEdited), "true", "false")
    End Get
End Property

And then in the javascript:

alert("The wasFieldEdited Value: <%= wasFieldEditedStatus %>" );

Solution 12 - Javascript

This is a cheat, but you can do this, send the value to sever side as a parameter

<script>
var myVar = "hello"
window.location.href = window.location.href.replace(/[\?#].*|$/, "?param=" + myVar); //Send the variable to the server side
</script>

And from the server side, retrieve the parameter

string myVar = Request.QueryString["param"];
Session["SessionName"] = myVar;

hope this helps

Solution 13 - Javascript

To modify session data from the server after page creation you would need to use AJAX or even JQuery to get the job done. Both of them can make a connection to the server to modify session data and get returned data back from that connection.

<?php
session_start();
$_SESSION['usedData'] = "Some Value"; //setting for now since it doesn't exist
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Modifying PHP Session Data</title>
        <script type='text/javascript'>
            var usedData = '<?php echo $_SESSION['usedData']; ?>';
            var oldDataValue = null;

            /* If function used, sends new data from input field to the
               server, then gets response from server if any. */

            function modifySession () {
                var newValue = document.getElementById("newValueData").value;

                /* You could always check the newValue here before making
                   the request so you know if its set or needs filtered. */

                var xhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
                
                xhttp.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {
                        oldDataValue = usedData;
                        usedData = this.responseText; //response from php script
                        document.getElementById("sessionValue").innerHTML = usedData;
                        document.getElementById("sessionOldValue").innerHTML = oldDataValue;
                    }
                };

            xhttp.open("GET", "modifySession.php?newData="+newValue, true);
            xhttp.send(); 
            }
        </script>
    </head>
    <body>
        <h1><p>Modify Session</p></h1>
        
        Current Value: <div id='sessionValue' style='display:inline'><?php echo $_SESSION['usedData']; ?></div><br/>
        Old Value: <div id='sessionOldValue' style='display:inline'><?php echo $_SESSION['usedData']; ?></div><br/>

        New Value: <input type='text' id='newValueData' /><br/>
        <button onClick='modifySession()'>Change Value</button>
   </body>
</html>

Now we need to make a small php script called modifySession.php to make changes to session data and post data back if necessary.

<?php
session_start();
$_SESSION['usedData'] = $_GET['newData']; //filter if necessary
echo $_SESSION['usedData']; // Post results back if necessary
?>

This should achieve the desired results you are looking for by modifying the session via server side using PHP/AJAX.

Solution 14 - Javascript

Here is what worked for me. Javascript has this.

<script type="text/javascript">
var deptname = '';
</script>

C# Code behind has this - it could be put on the master page so it reset var on ever page change.

        String csname1 = "LoadScript";
        Type cstype = p.GetType();

        // Get a ClientScriptManager reference from the Page class.
        ClientScriptManager cs = p.ClientScript;
        
        // Check to see if the startup script is already registered.
        if (!cs.IsStartupScriptRegistered(cstype, csname1))
        {
            String cstext1 = funct;
            cs.RegisterStartupScript(cstype, csname1, "deptname = 'accounting'", true);
        }
        else
        {
            String cstext = funct;
            cs.RegisterClientScriptBlock(cstype, csname1, "deptname ='accounting'",true);
        }

Add this code to a button click to confirm deptname changed.

alert(deptname);

Solution 15 - Javascript

i used my .php file to put required into sessions

> $_SESSION['name'] = $phparray["name"]; $ajaxoutput['name'] =$phparray["name"];

in my .js file i used

> sessionStorage.setItem("name", ajaxreturnedarray["name"]);

and i retrieved this using

> var myName= sessionStorage.getItem("name");

in other .js files or in same .js files

if i keep it as it is , it will return same at all times even you loggedout. so while logging out i made

> sessionStorage.setItem("name", "");

using this i emptied local variable. i used this process in single page website login/logout sessions. i hope this way will work for you because it worked for me. plz let me know your experiences.

Solution 16 - Javascript

I was able to solve a similar problem with simple URL parameters and auto refresh.

You can get the values from the URL parameters, do whatever you want with them and simply refresh the page.

HTML:

<a href=\"webpage.aspx?parameterName=parameterValue"> LinkText </a>

C#:

string variable = Request.QueryString["parameterName"];
if (parameterName!= null)
{
   Session["sessionVariable"] += parameterName;
   Response.AddHeader("REFRESH", "1;URL=webpage.aspx");
}

Solution 17 - Javascript

<?php
    session_start();
    $_SESSION['mydata']="some text";
?>

<script>
    var myfirstdata="<?php echo $_SESSION['mydata'];?>";
</script>

Solution 18 - Javascript

Possibly some mileage with this approach. This seems to get the date back to a session variable. The string it returns displays the javascript date but when I try to manipulate the string it displays the javascript code.

ob_start();
?>
<script type="text/javascript">
    var d = new Date();
    document.write(d);
</script>
<?
$_SESSION["date"]  = ob_get_contents();
ob_end_clean();
echo $_SESSION["date"]; // displays the date
echo substr($_SESSION["date"],28); 
// displays 'script"> var d = new Date(); document.write(d);'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMehmet InceView Question on Stackoverflow
Solution 1 - JavascriptSHEKHAR SHETEView Answer on Stackoverflow
Solution 2 - JavascriptDarrenView Answer on Stackoverflow
Solution 3 - JavascriptGaneshView Answer on Stackoverflow
Solution 4 - JavascriptRajeev KumarView Answer on Stackoverflow
Solution 5 - JavascriptQuentinView Answer on Stackoverflow
Solution 6 - JavascriptbtevfikView Answer on Stackoverflow
Solution 7 - JavascriptMohaimin MoinView Answer on Stackoverflow
Solution 8 - JavascriptBehnamView Answer on Stackoverflow
Solution 9 - JavascriptChandan RajbharView Answer on Stackoverflow
Solution 10 - JavascriptMatthieuView Answer on Stackoverflow
Solution 11 - JavascriptOff The GoldView Answer on Stackoverflow
Solution 12 - JavascriptKMRView Answer on Stackoverflow
Solution 13 - Javascriptshader2199View Answer on Stackoverflow
Solution 14 - Javascriptcode-itView Answer on Stackoverflow
Solution 15 - JavascriptSrinivasa ReddyView Answer on Stackoverflow
Solution 16 - JavascriptRui RuivoView Answer on Stackoverflow
Solution 17 - JavascriptPkdeView Answer on Stackoverflow
Solution 18 - JavascriptGordonView Answer on Stackoverflow