0

I am trying to create a variable through javascript and use that variable in my spring mvc controller. Unfortunately I can't seem to figure it out and the variable keeps coming up empty.

Here is my javascript where I set the variable:

<script language="JavaScript">
function checkBoxValues() {
    checkboxes = document.getElementsByName('message');

    var hopeThisWorks = "";
    for (var i = 0, n = checkboxes.length; i < n; i++) {
        if (checkboxes[i].checked == true) {
            message = checkboxes[i].value;
            var element = message.split(",");
            resubmitMessage(element[0], "" + element[1] + "",element[2]);
            var hopeThisWorks = "" + element[2] +"";
            alert(hopeThisWorks);
        }
    }

}
</script>

Then I take this variable and add it to my jsp as a input as follow:

 <input name="abc" type="hidden" value="${hopeThisWorks}">

Here is my code in my spring mvc controller:

@RequestMapping(method = RequestMethod.POST, value = "resubmit")
public String resubmit(@RequestParam(value = "abc") String param, Model model) {

    model.addAttribute("messageList", param);

    return RESUBMIT;
}

Then I call the variable in a jsp file to display the message as follows:

<table class="results table table-striped table-bordered table-condensed">
<thead>
<tr>
    <td colspan="10">
        <h5>Bulk Resubmit Query Results</h5>
    </td>
</tr>
<tr>
    <jsp:include page="../commons/a.jsp"/>
    <jsp:include page="../commons/b.jsp"/>
    <jsp:include page="../commons/c.jsp"/>
    <jsp:include page="../commons/d.jsp"/>
    <jsp:include page="../commons/e.jsp"/>
    <jsp:include page="../commons/f.jsp"/>
    <jsp:include page="../commons/g.jsp"/>
    <jsp:include page="../commons/h.jsp"/>
</tr>
<p>Test <c:out value="${messageList}"/></p>

5
  • rather than setting a JS variable, use JS to set the value to a input type=hidden element in your HTML form. or use Ajax to POST Commented Jan 13, 2017 at 7:30
  • I am using jsp files. Do you maybe have an example of how I can do that? I usually use input in the jsp file and not the javascript file. Commented Jan 13, 2017 at 7:34
  • 1
    I don't think you can do what you want, because of the order in which things happen. First, your Java runs on the server, and creates an HTML file. The JSP files can be used to create the HTML. The HTML is sent to the browser, which then runs the Javascript code. The variable won't be created until your Javascript method starts running, and by that time the HTML has already been created, so it's too late to get a Javascript variable in via JSP. As @ScaryWombat said, one solution is to have the Javascript modify the HTML directly (perhaps using jQuery). Commented Jan 13, 2017 at 7:36
  • So although I am creating a different page, it still is not possible? Commented Jan 13, 2017 at 7:50
  • I edited the question, I made some changes and still the value is empty, although I did save it in the form. Commented Jan 13, 2017 at 8:28

3 Answers 3

1

A good way to communicate variable ( or data ) between the client side and the server side is to use Ajax request. Even if you are in a .jsp you can use ajax ( with Jquery or Angular it's easier ). Here a exemple:

  function foo(){
        var data = '{"key":"'+value+'"}'; // here you create your json containing the var that you want to send to your server
        $.ajax({
            type : "POST",
            contentType : "application/json",
            url : "/theLocalisation", // here you put the "Url" of your spring mvc controller
            data : data,
            timeout : 100000,
            success : function(data) {
                var json = JSON.parse(data);
            //here it's the callback in the success case
            },
            error : function(e) {
                console.log("ERROR: ", e);
            },
            done : function(e) {
            }
        });
    }

Server side:

@RequestMapping(value = "/theLocalisationn")
    public String getTheStation(@RequestBody String data){
        // here you will receive your 
        JSONObject jsonObj = new JSONObject(search); //transform the string in JSON to use it.
        System.out.println(jsonObj); 
        //then do your magic here.

        return null;
    }

PS: I use the lib org.json and Jquery

Hoping this exemple will help you

Sign up to request clarification or add additional context in comments.

Comments

0

You can set the input value straight from javascript function. Better add id attribute to input:

<input id="abc" name="abc" type="hidden" value="">

And then in your javascript function:

<script language="JavaScript">
function checkBoxValues() {
    checkboxes = document.getElementsByName('message');

    var hopeThisWorks = "";
    for (var i = 0, n = checkboxes.length; i < n; i++) {
        if (checkboxes[i].checked == true) {
            message = checkboxes[i].value;
            var element = message.split(",");
            resubmitMessage(element[0], "" + element[1] + "",element[2]);
            var hopeThisWorks = "" + element[2] +"";
            document.getElementById("abc").value = hopeThisWorks;
        }
    }

}
</script>

Now the variable would be sent while submitting form.

Comments

0

you can't set the value of controller property without sending HTTP request, so after you have loaded the page you can send ajax request handle it by your controller and modify the property (in this case you will not be able to show the new value until refreshing), or send it in an input after setting the value of the input using JavaScript.

<input name="abc" type="hidden" id="myinput" value="${hopeThisWorks}">

<script language="JavaScript">
function checkBoxValues() {
    checkboxes = document.getElementsByName('message');

    var hopeThisWorks = "";
    for (var i = 0, n = checkboxes.length; i < n; i++) {
        if (checkboxes[i].checked == true) {
            message = checkboxes[i].value;
            var element = message.split(",");
            resubmitMessage(element[0], "" + element[1] + "",element[2]);
            var hopeThisWorks = "" + element[2] +"";
$("#myinput").attr("value",hopeThisWorks);
            alert(hopeThisWorks);
        }
    }

}
</script>

Comments

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.