how to print javascript variable to JSP Method

10,368

Javascript is ran on the client side and the jsp code is ran on the server. So when the jsp code is being run, v hasn't been initialized at all yet.

Why dont you just do this:

<script> 
    var v = "Javed";
    document.writeln(v);
</script>
Share:
10,368
Javed Salat
Author by

Javed Salat

Learning new things is my passion.

Updated on June 14, 2022

Comments

  • Javed Salat
    Javed Salat almost 2 years

    I am trying to print the java script variable to jsp page like

    <script> var v="Javed";</script><% String jspvar="<script>document.writeln(v);</script>";out.println("jspvar=======>>>>>>"+jspvar); 
    

    but in the output i am getting "document.writeln(v)". what should i do so get the value of variable . thank you

  • jlars62
    jlars62 almost 11 years
    I don't think that will work then. The jsp code is ran on the server and the javascript isn't ran until it has been sent to the client browser. So the jsp has no access to the javascript. Does that clarify anything or am I misunderstanding what you are looking for?
  • Javed Salat
    Javed Salat almost 11 years
    i came across the same code on one of the blog[www.roseindia.net/answers/viewqa/JSP-Servlet/9753-conve‌​rt-javascript-var-to‌​-java-variable.html]
  • jlars62
    jlars62 almost 11 years
    Interesting, method 1 looks good because the name variable is actually being sent back to the server ("a.jsp?name="+name) and then it is retrieved with String name=request.getParameter("name"). But from my understanding method 2 should not work. Here is some more information about it: coderanch.com/t/534263/JSP/java/… and stackoverflow.com/questions/3116058/…
  • jlars62
    jlars62 almost 11 years
    No problem, if you figure out that second method let me know.
  • jlars62
    jlars62 almost 11 years
    @javedsalat Also, as I am building my reputation, I would appreciate it if you voted up my answer if it was helpful! Thanks