13

Is it possible to access a String type variable defined in jsp from a javascript on the same page?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<title>Insert title here</title>
<script type="text/javascript">  
foo();
function foo()  
{  
var value = "<%=myVar%>";  
alert(value);   
}  
</script>  
</head>
<body>

<%

String myVar="blabla";
%>

</body>

</html>

In eclipse I am getting an error

myVar cannot be resolved to a variable
6
  • 1
    Where is your myVar defined? Commented Sep 24, 2013 at 19:48
  • 6
    <% and <%= blocks are evaluated in the order in which they're found on the page. You need to put the one that declares myVar before the one that uses it. Commented Sep 24, 2013 at 19:51
  • 5
    Although, ideally, you wouldn't use scriptlets at all. Commented Sep 24, 2013 at 19:51
  • 1
    Why not to use scriptlets? Commented Sep 24, 2013 at 19:57
  • 1
    possible duplicate of JSP Variable Accessing in JavaScript Commented Sep 24, 2013 at 20:00

1 Answer 1

27

This won't work since you're trying to use an undefined variable. The code is generated like this:

... = myVar;
//...
String myVar = "blabla";

Doesn't make sense, right? So, in order to make this work you should declare the variable before using it (as always):

<%
    String myVar="blabla";
%>
<script type="text/javascript">
    foo();
    function foo() {
        var value = "<%=myVar%>";
        alert(value);
    }
</script>

Still, usage of scriptlets is extremely discouraged. Assuming you're using JSTL and Expression Language (EL), this can be rewritten to:

<c:set name="myVar" value="blabla" />
<script type="text/javascript">  
    foo();
    function foo() {
        var value = "${myVar}";
        alert(value);
    }
</script>

If your variable has characters like " inside, then this approach will faile. You can escape the result by using <c:out> from JSTL:

var value = "<c:out value='${myVar}' />";

More info:

Sign up to request clarification or add additional context in comments.

6 Comments

@VgeShi I know, that was a recommendation.
what if myVar contains " characters? Isn't there a safe way to use it without escaping such characters manually??
@LuiggiMendoza i want the opposite of that . i want to get javascript value and pass it to java variable
@ShaabanEbrahim for that purpose, send a request to the server from your client side (javascript).
@LuiggiMendoza i want to encrypt password by method in java without need to send request to server
|

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.