-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.

5
  • As far as I know, that's just not possible. At least not the way you want. Commented May 20, 2016 at 6:55
  • then what is the other method possible to achieve the target Commented May 20, 2016 at 6: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. Commented May 20, 2016 at 7:00
  • 2
    this question has been answered many times, this is one of them stackoverflow.com/questions/8268356/… Commented May 20, 2016 at 7:03
  • @psyLogic Very good, marking as duplicate. Commented May 20, 2016 at 7:05

1 Answer 1

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");
    }
%>
Sign up to request clarification or add additional context in comments.

5 Comments

Shouldn't out.println(correct) be out.println(correct1)?
Shouldn't 'your_jsp_file.jsp?correct' = correct be 'your_jsp_file.jsp?correct=' + correct
@ErikKralj, thanks again :). I was so passionate about the process that did not pay attention to these errors
No problem, still missing an =. :D
@ErikKralj, checkmate :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.