How to get return value from javascript through JSP?

4.6k views Asked by At
function testing(){
    var e = document.getElementById("selectBranchId");
    var strUser = e.options[e.selectedIndex].value; 
    return strUser;
}

function test(){
    var resultValue = testing();
    alert(resultValue);
}

How can I get the value of resultValue in JSP? I tried using request.setAttribute but I am getting error variable resultValue can't be resolved. What can be the solution?

2

There are 2 answers

0
Ravi Roshan On

As JavaScript runs on the client side and JSP/Scriptlet is running on the server-side.

So if you want to access any of your JavaScript variable in JSP/Java/Server Side, then either

  1. Submit it as a Hidden form field
  2. or Pass it via Ajax Request
0
stisch On

The variable doesn't exist beforehand in the JspWriter. Consider your javascript in two categories; before the page is written and after.

<html>
        <head/>
        <body>
                <%!
                        function testing(){
                                var e = document.getElementById("selectBranchId");
                                var strUser = e.options[e.selectedIndex].value; 
                                return strUser;

                        }
                %>
                <% testing(); %>
        </body>
</html>

See this answer for more information.