[javascript] How to create a session using JavaScript?

How to create session in JavaScript?

I try like this:

<script type="text/javascript" >
{
Session["controlID"] ="This is my session";
}
</script> 

Why I looking for session?

I make a request for XML using AJAX. XML response I want to store in session and this session I want to pass to the server page(.asp). I mean to write something like:

<% response.write session("MySession")%>

This question is related to javascript asp.net session

The answer is


<script type="text/javascript">
function myfunction()
{
    var IDSes= "10200";
    '<%Session["IDDiv"] = "' + $(this).attr('id') + '"; %>'
    '<%Session["IDSes"] = "' + IDSes+ '"; %>';
     alert('<%=Session["IDSes"] %>');
}
</script>

link


If you create a cookie and do not specify an expiration date, it will create a session cookie which will expire at the end of the session.

See https://stackoverflow.com/a/532660/1901857 for more information.


Here is what I did and it worked, created a session in PHP and used xmlhhtprequest to check if session is set whenever an HTML page loads and it worked for Cordova.


Use HTML5 Local Storage. you can store and use the data anytime you please.

<script>
    // Store
    localStorage.setItem("lastname", "Smith");

    // Retrieve
    var data = localStorage.getItem("lastname");

</script>

I assume you are using ASP.NET MVC (C#), if not then this answer is not in your issue.

Is it impossible to assign session values directly through javascript? No, there is a way to do that.

Look again your code:

<script type="text/javascript" >
{
Session["controlID"] ="This is my session";
}
</script> 

A little bit change:

<script type="text/javascript" >
{
  <%Session["controlID"] = "This is my session";%>
}
</script>

The session "controlID" has created, but what about the value of session? is that persistent or can changeable via javascript?

Let change a little bit more:

<script type="text/javascript" >
{
  var strTest = "This is my session"; 
  <%Session["controlID"] = "'+ strTest +'";%>
}
</script>

The session is created, but the value inside of session will be "'+ strTest +'" but not "This is my session". If you try to write variable directly into server code like:

<%Session["controlID"] = strTest;%>

Then an error will occur in you page "There is no parameter strTest in current context...". Until now it is still seem impossible to assign session values directly through javascript.

Now I move to a new way. Using WebMethod at code behind to do that. Look again your code with a little bit change:

<script type="text/javascript" >
{
 var strTest = "This is my session"; 
 PageMethods.CreateSessionViaJavascript(strTest);
}
</script> 

In code-behind page. I create a WebMethod:

[System.Web.Services.WebMethod]
public static string CreateSessionViaJavascript(string strTest)
{
    Page objp = new Page();
    objp.Session["controlID"] = strTest; 
    return strTest;
}

After call the web method to create a session from javascript. The session "controlID" will has value "This is my session".

If you use the way I have explained, then please add this block of code inside form tag of your aspx page. The code help to enable page methods.

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

Source: JavaScript - How to Set values to Session in Javascript

Happy codding, Tri


You can store and read string information in a cookie.

If it is a session id coming from the server, the server can generate this cookie. And when another request is sent to the server the cookie will come too. Without having to do anything in the browser.

However if it is javascript that creates the session Id. You can create a cookie with javascript, with a function like:

The read function work from any page or tab of the same domain that has written it, either if the cookie was created from the page in javascript or from the server.


I think you misunderstood the concept of session, session is a server side per-user-data-store which allows you to save user data on the server side.

thus, you have 2 options, resort to use cookies, which will give the illusion of session(but not quite the same), you can access cookies very simply by document.cookie .

but, if you want your server be aware of the session, you need to use some sort of server request probably the best way is to use AJAX to do this.

I would recommend you to re-read the definition of sessions.


You can use the name attr:

<script type="text/javascript" >
{
window.name ="This is my session";
}
</script> 

You still have to develop for yourself the format to use, or use a wrapper from an already existing library (mootools, Dojo etc).
You can also use cookies, but they are more heavy on performance, as they go back and forth from the client to the server, and are specific to one domain.


function writeCookie(name,value,days) {
    var date, expires;
    if (days) {
        date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires=" + date.toGMTString();
            }else{
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

You can try jstorage javascript plugin, it is an elegant way to maintain sessions check this http://www.jstorage.info/

include the jStorage.js script into your html

<script src="jStorage.js"></script>

Then in your javascript place the sessiontoken into the a key like this

$.jStorage.set("YOUR_KEY",session_id);

Where "YOUR_KEY" is the key using which you can access you session_id , like this:

var id = $.jStorage.get("YOUR_KEY");

You can use Local storage.

local storage is same as session. the data will be removed when you close the browser.

<script> 
localStorage.setItem('lastname','Smith');

alert(localStorage.getItem('lastname'));
</script>

Edit: @Naveen comment below is correct. You can use session storage instead. (https://www.w3schools.com/jsref/prop_win_sessionstorage.asp) Thanks.

<script> 
sessionStorage.setItem('lastname','Smith');

alert(sessionStorage.getItem('lastname'));
</script>

You can use sessionStorage it is similar to localStorage but sessionStorage gets clear when the page session ends while localStorage has no expiration set.

See https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage


You can store and read string information in a cookie.

If it is a session id coming from the server, the server can generate this cookie. And when another request is sent to the server the cookie will come too. Without having to do anything in the browser.

However if it is javascript that creates the session Id. You can create a cookie with javascript, with a function like:

function writeCookie(name,value,days) {
    var date, expires;
    if (days) {
        date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires=" + date.toGMTString();
            }else{
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

Then in each page you need this session Id you can read the cookie, with a function like:

function readCookie(name) {
    var i, c, ca, nameEQ = name + "=";
    ca = document.cookie.split(';');
    for(i=0;i < ca.length;i++) {
        c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1,c.length);
        }
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length,c.length);
        }
    }
    return '';
}

The read function work from any page or tab of the same domain that has written it, either if the cookie was created from the page in javascript or from the server.

To store the id:

var sId = 's234543245';
writeCookie('sessionId', sId, 3);

To read the id:

var sId = readCookie('sessionId')

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 asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

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?