June 27, 2011

Equivalent of PHP Sessions in JavaScript

Question by user635614

I was going to ask about how to implement sessions in JS,I found few functions that can be used like this example I found :

String exforsys = request.getParameter("test"); 
session.setAttribute("test", exforsys);

And then just use session.getAttribute( exforsys);

But no response, I guess it’s only used in servlets or something.

Anyway, I decided that maybe someone has an alternative way other than just use sessions, what am trying to do is click on a link in one page and depending on which link was pressed I will load different information.

Since its a onclick function, I’m stuck with JS!

So I need to pass this information to the second page, cookies works well cause it can be handled with both PHP and JS easily but some computers deletes cookies and that wouldn’t be nice!

Any suggestions or other ways I can reach what I want but with out using sessions?

Answer by Starx

Sessions are server variables. Thus cannot be used by javascript.

However, you can retrieve the session variables, through ajax request

Script (jQuery)

//This portion will be triggerend once the dom is loaded and is ready
$(document).ready(function() {
    $.post("getsession.php",
       { "variable" : "yourneededsessionvariable" }, 
       fucntion(data) {
         //data containss your session data
       }
    );
});

PHP

//getsession.php
<?PHP
session_start();
echo $_SESSION[$_POST['variable']];
?>

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!