Question

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")%>
 45  357872  45
1 Jan 1970

Solution

 56

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')
2010-02-13

Solution

 19

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>
2014-05-08