- [javascript] How to access Session variables and set them in javascript?
- The answer is
- Read session in javascript
- # Table of Contents
- # How to access and set Session Variables in JavaScript
- # sessionStorage vs localStorage in JavaScript
- # Using the localStorage property to access and set variables
- # Additional Resources
[javascript] How to access Session variables and set them in javascript?
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
Accessing & Assigning the Session Variable using Javascript:
Assigning the ASP.NET Session Variable using Javascript:
Accessing ASP.NET Session variable using 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
Javascript can not directly set session values. For setting session values from javascript I do ajax call as follows.
$(function()< //Getting values from session and saving in javascript variable. // But this will be executed only at document.ready. var firstName = ''; var lastName = ''; $("#FirstName").val(firstName); $("#LastName").val(lastName); $('Button').click(function() < //Posting values to save in session $.post(document.URL+'?mode=ajax', ); >); >);
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
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.
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)
then call it from client side:
function ChangeSession(values)
you should set EnablePageMethods to true:
If you want read Session value in javascript.This code help for you.
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.
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
Edit : better example below, which you can try on phpfiddle.org, at the «codespace» tab
hello
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.
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
Add this code to a button click to confirm deptname changed.
This is a cheat, but you can do this, send the value to sever side as a parameter
var myVar = "hello" window.location.href = window.location.href.replace(/[\?#].*|$/, "?param param"]; Session["SessionName"] = myVar;
You could also set the variable in a property and call it from js:
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: " );
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.
string variable = Request.QueryString["parameterName"]; if (parameterName!= null)
i used my .php file to put required into sessions
$_SESSION['name'] = $phparray["name"]; $ajaxoutput['name'] =$phparray["name"];
and i retrieved this using
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
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.
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(); ?> var d = new Date(); document.write(d);'
Read session in javascript
Last updated: Apr 21, 2023
Reading time · 4 min
# Table of Contents
# How to access and set Session Variables in JavaScript
You can use sessionStorage.setItem() and the sessionStorage.getItem() method to access and set session variables in JavaScript.
The sessionStorage API enables you to store and access data saved in the current page session.
Here is the HTML for the example. It simply loads a JS script.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div id="id">bobbyhadz.comdiv> script type="module" src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!/** * Setting session variables */ sessionStorage.setItem('first', 'bobby'); sessionStorage.setItem('last', 'hadz'); const arr = ['dev', 'test', 'ship']; sessionStorage.setItem('tasks', JSON.stringify(arr)); // ----------------------------------- /** * Accessing session variables */ console.log(sessionStorage.getItem('first')); // 👉️ bobby console.log(sessionStorage.getItem('last')); // 👉️ hadz const parsed = JSON.parse(sessionStorage.getItem('tasks')); console.log(parsed); // 👉️ ['dev', 'test', 'ship']
The sessionStorage property is used to access a session Storage object for the current origin.
The setItem() method takes 2 parameters - a key and a value and sets the key-value pair on the Storage object.
Note that the key and the value have to be strings.
If you need to store an array or an object, make sure to use the JSON.stringify() method to convert the value to a string before storing it in sessionStorage .
Copied!sessionStorage.setItem('tasks', JSON.stringify(arr));
The getItem() method takes a key as a parameter and returns the corresponding value.
If you previously stored a JSON string, make sure to use the JSON.parse() method to parse the value back to a native JavaScript object.
Copied!sessionStorage.setItem('tasks', JSON.stringify(arr)); console.log(sessionStorage.getItem('first')); // 👉️ bobby
You can open the Console tab in your developer tools to look at the output of calling the sessionStorage.getItem() method.
# sessionStorage vs localStorage in JavaScript
There are 2 very similar APIs that allow you to access the Storage object:
The main difference between the two is that:
- Data stored using sessionStorage is only valid for the particular Tab. When the tab is closed, the data is cleared.
- Conversely, localStorage has no expiration and is not cleared when the Tab is closed.
When you open multiple tabs/windows with the same URL, a unique sessionStorage property is created for each tab/window.
On the other hand, the localStorage property is shared by all tabs/windows with the same URL.
You can view your localStorage and sessionStorage variables by opening your developer tools ( F12 ) and selecting the Application tab.
You can expand the Local Storage or Session Storage dropdown menus in the left sidebar.
Each menu shows the currently stored key-value pairs.
To better understand the difference between session storage and local storage:
Copied!/** * Setting session variables */ sessionStorage.setItem('first', 'bobby'); sessionStorage.setItem('last', 'hadz'); const arr = ['dev', 'test', 'ship']; sessionStorage.setItem('tasks', JSON.stringify(arr)); // ----------------------------------- /** * Accessing session variables */ console.log(sessionStorage.getItem('first')); // 👉️ bobby console.log(sessionStorage.getItem('last')); // 👉️ hadz const parsed = JSON.parse(sessionStorage.getItem('tasks')); console.log(parsed); // 👉️ ['dev', 'test', 'ship']
- If you open the Application tab in your developer tools and click on Session Storage, you will see that the key-value pairs have been set.
- Now comment out the code or remove it.
- Close the browser tab and reopen it.
- If you open the Application tab in your developer tools and click on Session storage, you will see that the key-value pairs have been removed.
Data stored using sessionStorage is only valid for the particular Tab. When the tab is closed, the data is cleared.
# Using the localStorage property to access and set variables
Let's look at an example of using the localStorage property to access and set variables that are saved across browser sessions.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div id="id">bobbyhadz.comdiv> script type="module" src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!/** * Setting variables that are saved across browser sessions */ localStorage.setItem('first', 'bobby'); localStorage.setItem('last', 'hadz'); const arr = ['dev', 'test', 'ship']; localStorage.setItem('tasks', JSON.stringify(arr)); // ----------------------------------- /** * Accessing the variables */ console.log(localStorage.getItem('first')); // 👉️ bobby console.log(localStorage.getItem('last')); // 👉️ hadz const parsed = JSON.parse(localStorage.getItem('tasks')); console.log(parsed); // 👉️ ['dev', 'test', 'ship']
If I open the Console tab, I can see that the values are logged to the console.
You can also click on the Application tab and select Local Storage in the left sidebar.
As with the sessionStorage API, the setItem() method takes 2 strings - a key and a value.
If you need to store an array or an object in localStorage , make sure to stringify it.
Copied!localStorage.setItem('tasks', JSON.stringify(arr));
When you need to retrieve the data, make sure to parse it to a native JavaScript object.
Copied!const parsed = JSON.parse(localStorage.getItem('tasks'));
The benefit of using localStorage is that the data is preserved after you close the tab.
To better illustrate how this works:
Copied!/** * Setting variables that are saved across browser sessions */ localStorage.setItem('first', 'bobby'); localStorage.setItem('last', 'hadz'); const arr = ['dev', 'test', 'ship']; localStorage.setItem('tasks', JSON.stringify(arr)); // ----------------------------------- /** * Accessing the variables */ console.log(localStorage.getItem('first')); // 👉️ bobby console.log(localStorage.getItem('last')); // 👉️ hadz const parsed = JSON.parse(localStorage.getItem('tasks')); console.log(parsed); // 👉️ ['dev', 'test', 'ship']
- If you open the Application tab in your developer tools and click on Local Storage, you will see that the key-value pairs have been set.
- Now comment out the code or remove it.
- Close the browser tab and reopen it.
- If you open the Application tab in your developer tools and click on Local storage, you will see that the key-value pairs persist between sessions.
This is because localStorage has no expiration and is not cleared when the Tab/Window is closed.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.