Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read session variable in javascript?

I am setting session variable in servlet and want to access that variable in javascript.

 ps = con.prepareStatement("select * from USERDETAILS where username=? and password=?");
 ps.setString(1, username);
 session.setAttribute("userName", username);

I tried these in javascript function. but it wasn't working...

var name = ${userName};
var name = '<%= Session["userName"] %>';
like image 423
Bobby Rachel Avatar asked Aug 02 '13 05:08

Bobby Rachel


People also ask

Can JavaScript read session variables?

Javascript can not directly set session values.

How do you access session variables in HTML?

As a HTML page is served as is, with no code running on the server, it cannot access the session. You'd need to make it an ASP.NET page, or a PHP page, or whatever other framework your other pages are running in. Then you can access the Session, the same as with your other pages. Please Sign up or sign in to vote.

Can JavaScript access PHP session variable?

Your answer Hello @kartik, You can't set a server session variable directly from JS.


1 Answers

Seems you should be able to use getAttribute():

var name = '<%= session.getAttribute("userName") %>';

Though, this depends on Java running through the file to replace the embedded <%= ... %>, which probably won't be the case in separate .js files.

like image 67
Jonathan Lonowski Avatar answered Sep 22 '22 06:09

Jonathan Lonowski