tags:

views:

67

answers:

3

How can I access an JavaScript variable from within an JSP page ?

A: 

Not possible. You can access a JSP variable in javascript but the javascript variable can not be accessed in JSP.

RaviG
You can't *"access a JSP variable in [client-side] javascript"*. You can send the variable's *value* to the client by outputting it within the Javascript code in a server-generated `script` block, which isn't the same thing.
T.J. Crowder
Can you explain if it is possible to do it other way round ?
Rachel
+3  A: 
T.J. Crowder
Can you provide an example of how can I access and client side variable's value on the server side ?
Rachel
@Rachel: you would need either JavaScript make a request to the server (AJAX) or populate a form with the values and submit that.
Dormilich
@Rachel: I added some examples
T.J. Crowder
@T.J.Crowder: Thank you for the example, now am able to understand this concept more clearly.
Rachel
@Rachel: Excellent! Glad that helped.
T.J. Crowder
I down voted your answer, because it seems you are answering a perfectly valid question that was not asked.
@austin: I guess you kind of missed the minor detail that the **OP** felt I'd answered her question. You know, what with her comments, and that big green checkmark. Downvoting is pretty darned silly given that evidence.
T.J. Crowder
+1  A: 

You can't access it directly. That's because this is how a page is rendered:

1. On the server, the JSP code runs and generates HTML/JavaScript.
2. The HTML/JavaScript is sent to the client's browser. 
3. The browser then renders the HTML and runs the JavaScript.

As you can see, the JavaScript is run way after the JSP runs, so they can't directly access each other's variables.

What you could do is output JavaScript code which initializes a variable based on a value in the JSP code. For example, if you generate code like this (excuse my syntax, I don't know JSP):

<script>
    var JSPValue = /*jsp code that prints the value of a variable*/;
    //rest of JavaScript code...
</script>

Then the JavaScript can accss JSPValue, just because it will have been put there by the server. For example, when sent to the browser, it might look like:

<script>
    var JSPValue = 42;
    //rest of JavaScript code...
</script>
Claudiu
You suggestion of creating a global JavaScript variable does answer the question, but is not a recommended best practice. Dynamic creation of arbitrary global variables from JSP tends to lead developers who do not write for JavaScript primarily into a false sense of functionality that is prone to namespace collisions and unexpected code failure.