11

I want to access Javascript variables in JSP code. How can I do that?

0

3 Answers 3

11

JavaScript variable is on client side, JSP variables is on server side, so you can't access javascript variables in JSP. But you can store needed data in hidden fields, set its value in client and get it on server over GET or POST.

Client side:

<script type="text/javascript">
var el = document.getElementById("data");
el.value = "Needed_value";
</script>
<form action="./Your_JSP.jsp" method="POST">
<input id="data" type="hidden" value="" />
<input type="submit" />
</form>

server side:

<%
if (request.getParameter("data") != null) { %>
 Your value: <%=request.getParameter("data")%>
<%   
} 
%>
Sign up to request clarification or add additional context in comments.

1 Comment

Beware of "Cross-Site Scripting" issues here.
3

I came across the same issue. I wanted to fetch couple of data in jsp. What I did is, in javascript function I concatenated the data in one variable with delimiter and passed that variable in parameter like this.

function myname()
 {
var fname = "FirstName";
var lname = "LastName";
var fullname = fname+","+lname;
document.location.href = "demopage.jsp?name="+fullname;
}

And then in jsp page, we can fetch the full name as,

<c:set var="varname" value='<%= request.getParameter("name") %>' />

Now we can split the first name and last name using delimiter ','.

Comments

0
function call()

   {
    var name="xyz";
    window.location.replace=("a.jsp?m="+name);
   }

 String name=request.getParameter("name");

 if(name!=null){
    out.println(name);        
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.