Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of PHP Sessions in JavaScript

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?

like image 669
dimazaid Avatar asked May 30 '26 13:05

dimazaid


2 Answers

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 triggered once the DOM is loaded and is ready
$(document).ready(function() {
    $.post("getsession.php",
       { "variable" : "yourneededsessionvariable" }, 
       function(data) {
         //data contains your session data
       }
    );
});

PHP

//getsession.php
<?PHP
session_start();
echo $_SESSION[$_POST['variable']];
?>
like image 51
Starx Avatar answered Jun 01 '26 04:06

Starx


Use local storage or client controlled cookies.. Sessions uses server-controlled cookies. Cookies are just small files that resided on the client.

like image 29
CS_2013 Avatar answered Jun 01 '26 04:06

CS_2013



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!