Ryan Swanson
Ryan Swanson

Reputation: 89

Trying to pass an array of data to a Spring MVC Controller using Ajax

I writing code to send data from javascript to a Spring MVC Controller using Ajax.

It appears that my Ajax code is working fine as my "success" message is printed in the client console, so I am assuming the POST was executed. However, my Controller doesn't seem to be getting called as its message is never printed to the server console.

My Ajax code:

<script>
            $(document).ready(function () {
                $("#submit-btn-2").on("click", function () {
                    var idList = [];
                    $(".vm-row").has(":checkbox:checked").each(function() {
                        idList.push($(this).attr('id'));
                    });
                    $.ajax({
                        type: "POST",
                        url: 'submitVendors',
                        data: {idList:idList},
                        success: function(id) {
                            console.log("SUCCESS: ", idList);                           
                        },
                        error : function(e) {
                            console.log("ERROR: ", e);
                        },
                        done : function(e) {
                            console.log("DONE")
                        }
                    })
                });
            });
</script>

Clicking the associated button causes this message to be printed to the client console:

SUCCESS:  Array(3)

My Controller:

@RequestMapping(value="/submitVendors", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody 
    String submitVendors(@RequestParam("idList[]") String[] idList, HttpServletRequest request) {

        String vid = request.getSession().getAttribute("vid").toString();
        System.out.println("Inside submitVendors service.");

        for (String id : idList)
        {
            System.out.println("It actually worked: " + id);
        }

        return "vendormanagement";
    }

No error of any sort is printed to the server console and neither are messages.

Upvotes: 0

Views: 68

Answers (2)

corroborator
corroborator

Reputation: 321

Try this :

data: JSON.stringify(idList), and (@RequestBody String[] idList)

OR this :

data: {"idList":idList.toString()}, and (@RequestParam(value = "idList") List<String> idList)

Upvotes: 2

Lakshan
Lakshan

Reputation: 1436

pass the RequestParam name mached with variable name return by ajax,

@RequestParam(value="idList") ArrayList<String> idList)

add/ change the following properties into/ in ajax function

dataType: 'json',
data:{idList : idList.toString()}

Upvotes: 0

Related Questions