85
votes

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?

18
Please state whether it is ASP.Net MVC or Webforms. If MVC, you can access it directly to javascript. If webforms, you can temporarily add to ViewState[]Fendy
I'am using WebForms, why I cannot access Session variable and set it a value?Mehmet Ince
Not too through into WebForms, it is new to me to direct access to Session in WebForm (though it is most likely bad practice). Session is in server side (webserver / iis), and javascript is at client side (browser). You need specific request to webserver to trigger change at session. In short, you can update the session from javascript using ajax (jQuery for simpler implementation) and webservice.Fendy

18 Answers

63
votes

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>
27
votes

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

15
votes

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.

13
votes

Try This

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

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.

4
votes

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

2
votes

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.

2
votes

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>
2
votes

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

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

1
votes

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 %>" );
1
votes

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.

1
votes

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

1
votes

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.

1
votes

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

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.

0
votes

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");
}
-1
votes
<?php
    session_start();
    $_SESSION['mydata']="some text";
?>

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

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