How to set/get session values from javascript

javascript, session

Solution

you can't access server session in client side. but if you want to do some changes in client side according to server session value. i will give you small idea.it may work for you.

(sorry, I know only java not php,etc.,)

just inside JSP script-let check for the session, create some hidden html element with session value. like this

<% String role=request.getSession().getAttribute("role").toString();%>
<input type="hidden" id="role" value=<%= role ;%> />

And then ,in javascript just get the role from html input element by ID like this.

var role=document.getElementById("role");

and do you stuff here.

And if you want to set role in session in javascript, it may help you

    <script>
function nameYourFunction()
{
    var role="";

    if(your condition)
    <% request.getSession().setAttribute("your variable","your values"); %>
}

</script> 

hope this works. And call your function, whenever you need.

Problem

I want to access to session in javascript code so as to set and get some values : i try with this code : ``` function getsessionvalue() { var value= '<%= session["role"].ToString() %>'; alert(value); //var role1= '<%= session["role"] %>'; **the same mistake** //alert(role1); } ``` but i have these javascript mistakes for both : ``` The type of the expression must be an array type but it resolved to Type mismatch: cannot convert from String to int ```

Original source

Related problems