Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set/get session values from javascript

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
like image 237
lilyana Avatar asked Feb 12 '23 22:02

lilyana


1 Answers

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.

like image 144
user3662273 Avatar answered Feb 15 '23 12:02

user3662273