-2

I am trying to convert a javascript variable to a jsp variable like this

var correct=9;

<%int correct1%>=correct;

But it gives syntax error.

Vibhesh Kaul
  • 2,593
  • 1
  • 21
  • 38
zlareb1
  • 44
  • 2
  • 9
  • As far as I know, that's just not possible. At least not the way you want. – erikvimz May 20 '16 at 06:55
  • then what is the other method possible to achieve the target – zlareb1 May 20 '16 at 06:57
  • You can allocate Java variables to Javascript to be run when the page is loaded but it can't go the other way around. If you wanted to pass a Javascript variable to JSP you'd have to make an Ajax request, open a new page or post a form. – erikvimz May 20 '16 at 07:00
  • 2
    this question has been answered many times, this is one of them http://stackoverflow.com/questions/8268356/assign-javascript-variable-to-java-variable-in-jsp – Vibhesh Kaul May 20 '16 at 07:03
  • @psyLogic Very good, marking as duplicate. – erikvimz May 20 '16 at 07:05

1 Answers1

0

You can set a data in your JavaScript code from JSP, but not reverse. Something like this:

var correct = <% int correct1 = 1; out.println(correct1); %>;

If you want to transfer JavaScript variable's value to the server side, you have to do It only with form data posting or ajax.

Sample:

HTML file:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
    var correct = 9;

    $.ajax({

        url: 'your_jsp_file.jsp?correct=' + correct,
        method: 'get',
        success: function(result) {

            alert(result);
        }
    });
</script>

JSP file (your_jsp_file.jsp):

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
    int correct1;

    if (request.getParameter("correct") == null) {

        out.println("error");
    } 
    else {

        String param = request.getParameter("correct");

        if (param.matches("^[0-9]+$")) {

            correct1 = Integer.parseInt(param);
        }

        out.println("ok");
    }
%>
Ali Mamedov
  • 5,116
  • 3
  • 33
  • 47