Kleber Mota
Kleber Mota

Reputation: 9065

Spring controller method don't recognize parameter passed by jquery .ajax() function

In my project, I have the following .ajax() function, which should send the content of a with multiple values to the server:

$("#btn_enviar").click(function(){
    var selecao_usuario=[];
    $('#selecao option').each(function(){
        selecao_usuario.push($(this).val());
    });
    $.ajax({
        url: "lista_horario.html",
        data: { id_usuarios: selecao_usuario, id_evento: $('#id_evento option:selected').val() },
        cache: false
    }).done(function(data) {
        $("#result").show();
        $("#result").empty().append( data );
    });
});

What happens is that, according to browser console, this is the parameters this function is sending to server:

id_evento "1"
id_usuarios[] "9"
id_usuarios[] "4"
id_usuarios[] "7"
id_usuarios[] "8"

and because this last parameter, I am getting this error from server:

HTTP Status 400 - Required String[] parameter 'id_usuarios' is not present

type Status report

message Required String[] parameter 'id_usuarios' is not present

description The request sent by the client was syntactically incorrect.
Apache Tomcat/7.0.42

the function above is sending the data for this method from my spring controller:

@RequestMapping(value="/lista_horario", method=RequestMethod.GET)
@ResponseBody
public String lista_horario(@RequestParam("id_evento") String id_evento, @RequestParam("id_usuarios") String[] usuarios)
{
     ...
     }

Upvotes: 0

Views: 1034

Answers (2)

Maciej Walkowiak
Maciej Walkowiak

Reputation: 12932

Param name in Spring MVC has to match param name in request. In your case change param name from @RequestParam("id_usuarios") to @RequestParam("id_usuarios[]").

Upvotes: 1

Oscar Paz
Oscar Paz

Reputation: 18292

The last parameter is sent because of the cache: false option in the ajax call. To prevent caching of the response, jQuery adds the parameter _ with a value that equals the current timestamp (the result of Date.now()). This way, the request is always different and is not cached by the browser. If it is causing problems, then disable the cache via server response headers and remove the cache parameter from your call to ajax(). I'm not sure, though, that this is the reason why you're getting an error. Try removing the argument and see if it works.

Upvotes: 0

Related Questions