[javascript] 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?

This question is related to javascript .net session

The answer is


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.


Try This

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

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.


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


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

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


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

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.


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

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

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


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


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>

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

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

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.


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

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.


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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to session

What is the best way to manage a user's session in React? Spring Boot Java Config Set Session Timeout PHP Unset Session Variable How to kill all active and inactive oracle sessions for user Difference between request.getSession() and request.getSession(true) PHP - Session destroy after closing browser Get Current Session Value in JavaScript? Invalidating JSON Web Tokens How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session How can I get session id in php and show it?