45

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")%>
Alex Kulinkovich
  • 4,408
  • 15
  • 46
  • 50
Alex
  • 1,933
  • 9
  • 36
  • 40

13 Answers13

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')
Mic
  • 24,812
  • 9
  • 57
  • 70
  • I think in the first block, it should be like, `document.cookie = name + "=" + value + ";expires=" + expires + "; path=/";` – Max Jun 17 '14 at 19:38
  • @user3526, the expires variable contains already the string `;expires=`, so no need to add it again. Cheers, – Mic Jun 20 '14 at 10:18
  • @Mic the document.cookie is returning an empty string for me – Zeeshan Ahmad Khalil Nov 02 '19 at 16:38
  • @ZeeshanAhmadKhalil did you try the same example above with "s234543245" or your own ? – Mic Nov 04 '19 at 10:56
  • He asked about session, you answered about cookie :( The answer should be about `sessionStorage.setItem("sessionID", "value");` This will store the data only in session (deleted after closing the page) – Freelancer Feb 27 '21 at 04:02
  • @Freelancer he asked at the end to get that information back to the server, so 11 years after we don't know exactly what he wanted to do ;) – Mic Mar 02 '21 at 09:27
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>
Rafael M.
  • 211
  • 2
  • 7
  • 9
    nope, you need to use session storage, session storage stores per session localstorage doesnt have expiry. – Naveen Mar 28 '15 at 13:46
11

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

Tri Nguyen Dung
  • 929
  • 2
  • 13
  • 24
11

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.

MindFold
  • 771
  • 5
  • 16
  • 1
    why i looking for session is , i make a request for xml using ajax.. xml response i want to store in session and this session i wand to pass to the server page (.asp). that means, if i write <% response.write session("MySession")%> – Alex Feb 13 '10 at 13:27
  • Session resids on the server side, you can't pass "session" to the server, unless you mean sessionID, but you still need to initiate the session on the server, what you must mean is cookies, you can simply store that data in a cookie and re-send it from there, session is NOT the correct term. – MindFold Feb 13 '10 at 19:28
  • According to this -> http://www.thefreedictionary.com/session , you are able to interpret the word session as something that can be used on the client side as well. Let's not narrow our options here.. In my head a session (be it a DB session, a transaction, web session) is a series of operations that belongs together with a beginning and an end. – Lars Juel Jensen Aug 07 '14 at 10:55
1

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");
Jibin Mathew
  • 4,816
  • 4
  • 40
  • 68
1

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

Rim Gazzah
  • 571
  • 1
  • 6
  • 13
1
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=/";
}
Dre
  • 4,298
  • 30
  • 39
gaurav
  • 11
  • 1
  • a session cookie doesn't have an expiry date http://en.wikipedia.org/w/index.php?title=HTTP_cookie&section=3#Session_cookie – Bevan Collins Feb 26 '13 at 00:13
0

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.

0

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.

Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278
  • why i looking for session is , i make a request for xml using ajax.. xml response i want to store in session and this session i wand to pass to the server page (.asp). that means, if i write <% response.write session("MySession")%> – Alex Feb 13 '10 at 13:26
0

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.

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

link

Community
  • 1
  • 1
mohammad
  • 360
  • 3
  • 8
  • this is not a good practice it's server-side/runtime and it will execute only on page loading the best way is to use sessionStorage as mentioned below – Mohammad Al Baghdadi Dec 12 '16 at 19:39
0

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.

-1

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>