Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")%> 
like image 565
Alex Avatar asked Feb 13 '10 13:02

Alex


1 Answers

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') 
like image 130
Mic Avatar answered Sep 27 '22 02:09

Mic