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']];
?>