1

How can I pass the value of a variable from javascript to a java variable?

<% String st = "<script>document.writeln(selected)</script>";
 out.print("value = " + st);%>

This is my code for java getting the values from javascript variable, selected. But no value is displayed.

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
T E M
  • 55
  • 1
  • 2
  • 8
  • 1
    Javascript executes on client side, Java executes on server side. You cannot pass values between these two directly. – Pradeep Simha Dec 26 '12 at 08:40
  • Hmm.. then how can i make them communicate knowing that they are in different side of programming? :) – T E M Dec 26 '12 at 08:42
  • possible duplicate of [javascript to jsp](http://stackoverflow.com/questions/4886229/javascript-to-jsp) – Thilo Dec 26 '12 at 08:44
  • <% String st = ""; out.print("value = " + st);%> this is my code for java getting the values from javascript variable, selected. but no value is displayed – T E M Dec 26 '12 at 08:49

4 Answers4

3

You have to make a request and send your variable from the browser (where Javascript lives) to the server (where the JSP lives) that way.

Ajax would work, or an HTML form.

In you JSP, you can then receive it as a request parameter (or as part of the request body, or as a request header).

Thilo
  • 257,207
  • 101
  • 511
  • 656
2

Javascript runs on client. JSP runs on server. The only way to pass information from client to server in web environment is via HTTP parameters or HTTP headers during HTTP request or as a part of request body if method is POST or PUT.

So, you should create such request. It can be done using either changing of your document location or utilizing AJAX call.

AlexR
  • 114,158
  • 16
  • 130
  • 208
  • <% String st = ""; out.print("value = " + st);%> this is my code for java getting the values from javascript variable, selected. but no value is displayed. – T E M Dec 26 '12 at 08:44
2

you can pass parameter or make a hidden field inside your jsp code and using javascript assign value for this hidden field, then get parameter value in java code.

Manish Nagar
  • 1,038
  • 7
  • 12
1

Use HTML forms.

On server side, you'll get the data in HTTPServletRequest parameter.

Check this too: Building my first Java Web Application

Community
  • 1
  • 1
Azodious
  • 13,752
  • 1
  • 36
  • 71