94

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?

Karl Fazer
  • 57
  • 1
  • 8
Mehmet Ince
  • 4,059
  • 12
  • 45
  • 65
  • 3
    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 Mar 20 '13 at 09:19
  • I'am using WebForms, why I cannot access Session variable and set it a value? – Mehmet Ince Apr 29 '13 at 09:31
  • 1
    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 Apr 29 '13 at 10:05

18 Answers18

72

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>
user2316116
  • 6,726
  • 1
  • 21
  • 35
SHEKHAR SHETE
  • 5,964
  • 15
  • 85
  • 143
  • Can We retrieve this Session value in .cs file? – Rajshekar Reddy Jan 21 '14 at 14:34
  • 8
    I tried you code exactly and the output I get when I access it in my code the output is `+ userName +` – Rajshekar Reddy Jan 23 '14 at 04:16
  • 26
    This answer is not going to work. Invoking the SetUserName method is not going to make a call to the server to access the Session object – mcintyre321 Apr 14 '14 at 09:02
  • Not workable, you cannot set session from javascript directly, The example provided is also just a Hack, not actually setting session. – Nitin Garg Feb 15 '16 at 14:29
  • 3
    answer is not working still it is getting upvotes . i think answer needs to be reviewed – Heemanshu Bhalla May 06 '16 at 16:26
  • 1
    @HeemanshuBhalla Actually the answer is getting upvotes cause the accessing part works like a charm. Haven't checked the Assigning part though. – Ahmad Maleki Jul 17 '16 at 12:29
  • 4
    The "Accessing" part work. But BIG caveat: It will only be assigned once at page Creation. The server assigns the value when rendering the JavaScript. You can re-execute the JavaScript on a partial postpack with a pagelaad() but if your postback changes the new sessionVariable will not be assigned to the JavaScript. It will just reuse the old one. – DaniDev Nov 15 '16 at 00:44
  • js will render in front end. setting session from js is a security issue, therefore it is not possible. – autopilot Jul 15 '17 at 11:37
  • 1
    Calling `SetUserName()` - function in JavaScript won't add data to the session. To do this you need to make a request to the Server - AJAX, Form submit. – P R Oct 11 '17 at 08:38
  • Hi, you should rather use Ajax for the purpose. Define a method in your page. e.g.[WebMethod] [ScriptMethod] public static string setProductIDForPlanning(string ID) { HttpContext.Current.Session["FPID"] = ID; return "|"; } – Muhammad Aamir Iqbal May 03 '18 at 06:54
  • 1
    In .NET I had to change the [] square barackets to () Parenthesis – R2 Builder Jan 04 '19 at 20:04
  • This answer in now way retrieves a session object, it just alerts a string. – Robert Jun 18 '19 at 15:43
30

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

Darren
  • 68,902
  • 24
  • 138
  • 144
15

Try This

var sessionValue = '<%=Session["usedData"]%>'
Rajeev Kumar
  • 4,901
  • 8
  • 48
  • 83
  • thanks, that works great :) but I want to set also session value, is this possible? – Mehmet Ince Mar 20 '13 at 09:21
  • @MehmetInce, to set the Session value you would to send the value to the server through a post or get and have the server handle the request. There is nothing stopping you doing this request through ajax. – Ash Burlaczenko Mar 20 '13 at 09:31
  • 1
    @AshBurlaczenko Could you please post a sample example for this. It would be of great help – Rajeev Kumar Mar 20 '13 at 09:32
  • 1
    But, how will you assign value to Session Variable using Javascript? – SHEKHAR SHETE Nov 27 '13 at 07:30
  • If I do this in `file.js` in a function `$button.click` all I get is the pure string from the assignment. Have there been some changes in javascript since 2013? – bomben Jul 25 '23 at 13:08
15

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.

Ganesh Nemade
  • 1,504
  • 12
  • 17
12

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
5

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

btevfik
  • 3,391
  • 3
  • 27
  • 39
  • 1
    good point to have easy access but big problem to code security, user can tricky change his account user/access using tools like devTool in chrome and do what is not allowed by his access level – Saghachi Oct 07 '20 at 07:06
2

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.

X-Coder
  • 2,632
  • 2
  • 19
  • 17
Mohaimin Moin
  • 821
  • 11
  • 22
2

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>
Behnam
  • 1,039
  • 2
  • 14
  • 39
2

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

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

2

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);
code-it
  • 81
  • 4
1

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.

Precious Tom
  • 486
  • 3
  • 18
Matthieu
  • 39
  • 4
1

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 %>" );
Off The Gold
  • 1,228
  • 15
  • 28
1

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

kas_miyulu
  • 335
  • 1
  • 5
  • 27
1

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.

shader2199
  • 25
  • 6
0

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

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");
}
Rui Ruivo
  • 343
  • 3
  • 12
-1
<?php
    session_start();
    $_SESSION['mydata']="some text";
?>

<script>
    var myfirstdata="<?php echo $_SESSION['mydata'];?>";
</script>
David Buck
  • 3,752
  • 35
  • 31
  • 35
Pkde
  • 1
  • The provided answer was flagged as low quality. Here are some tips on [How to answer?](https://stackoverflow.com/help/how-to-answer) – Guilherme Lemmi Oct 03 '20 at 05:22
-1

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);'
Gordon
  • 1