Kamal Pundir
Kamal Pundir

Reputation: 277

Updating JSP variable value in JavaScript code

I want to update a JSP variable value from a Java Script code (JS code is in different file). Means a JSP variable to be updated from a included .JS file code

Upvotes: 0

Views: 7864

Answers (2)

Anthony Grist
Anthony Grist

Reputation: 38345

JSP is run server-side (on the server), whereas JavaScript is run client-side (in the browser). The two can't communicate directly.

You can create a JavaScript variable with the value of your JSP variable (in your JSP file):

<script type="text/javascript">
    var myJspVariable = '<%= myJspVariable %>';
</script>
<script type="text/javascript" src="myJavascriptFile.js"></script>

then you can work with myJspVariable in your other .js file. However, that won't update the value on the server - if you need to do that, you'll have to make an AJAX request to post the value back.

Upvotes: 2

adarshr
adarshr

Reputation: 62583

It can't be done. JSP is executed on the server and JavaScript on the browser.

What you can instead do, is send an HTTP (GET or POST) request to the JSP and use it to update the variable.

Upvotes: 3

Related Questions