views:

30

answers:

3

How do I pass Javascript variable to and JSTL?

<script>

    var name = "john";  

    <jsp:setProperty name="emp" property="firstName" value=" "/>   // How do I set javascript variable(name) value here ?

    <c:set var="firstName" value=""/>  // How do I set javascript variable (name) value here ?     

  </script>
+1  A: 
<script>
var name = "<jsp:getProperty name="emp" property="firstName" />";
</script>

The JSP code executes before the JavaScript so by the time the JavaScript gets processed the tag will be replaced with the contents of emp.firstName.

Russ
JSTL Version:<script>var name = "<c:out value="${emp.firstName}"/>";</script>
Russ
He's asking how to pass data from JavaScript to JSTL, not the other way around.
Stian
+1  A: 

AFAIK you can't send data from JavaScript to JSTL that way. Because the JSTL tags are handled serverside, so the <jsp:> tags will be parsed on the server and replaced by HTML. So the <jsp:> tags won't be a part of the response that is sent back to the client; it will consist only of HTML/text. Therefore you can't access the <jsp:> tags from JavaScript, because they won't exist in the document.

Edit: sorry, the <jsp:> tags wasn't visible.

Stian
+2  A: 

You need to send it as a request parameter. One of the ways is populating a hidden input field.

<script>document.getElementById('firstName').value = 'john';</script>
<input type="hidden" id="firstName" name="firstName">

This way you can get it in the server side as request parameter when the form is been submitted.

<jsp:setProperty name="emp" property="firstName" value="${param.firstName}" />

An alternative way is using Ajax, but that's a completely new story/answer at its own.

See also:

If you can't seem to find your previously asked questions back, head to your user profile!

BalusC