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"] %>';
Javascript can not directly set session values.
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.
Your answer Hello @kartik, You can't set a server session variable directly from JS.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With