Search code examples
javaajaxspring-bootjquery-select2jquery-select2-4

Select2 search term is not being sent to my controller endpoint


I have a select2 (which uses AJAX request to fetch data from remote source, in my case a SpringBoot API). I managed to fetch the data I wanted. However, I'm having trouble to receive in my endpoint the search term, so I can filter the results based on what the user types:

Right below is my code, both AJAX request with select2 and my SpringBoot endpoint with the corresponding function.

$(".select2-single").select2({
     ajax: {
        url: 'http://localhost:8080/credenciamento/busca-procedimentos/',
        dataType: 'json',
        delay: 500,
        data: function (params) {
           console.log(params.term);
           return {
                q: params.term, // search term
           };
        },
        processResults: function (response) {
            var procedures = [];
            for (let i = 0; i < response.length; i++) {
                procedures.push({
                    id: response[i].id, 
                    text: response[i].descricao
                })
            }
            return { results: procedures }
        },
        cache: true,
    },
});

And here, my Java function:

@GetMapping(path = "/credenciamento/busca-procedimentos/")
@ResponseBody
public List<Procedimento> buscaProcedimentos(@PathVariable(value = "q", required = false) String query) {
    System.out.println(query);

    List<Procedimento> procedimentos = procedimentoService.findAll();
    int size = procedimentos.size();

    if (StringUtils.isEmpty(query)) {
        return procedimentos.subList(0, size);
    }

    Procedimento[] procedimentosArray = new Procedimento[size];
    procedimentosArray = (Procedimento[]) procedimentos.toArray();

    return (List<Procedimento>) Arrays.stream(procedimentosArray)
    .filter(procedimento -> 
            procedimento.getDescricao().toLowerCase().contains(query)
    ).limit(2);
}

PS: everytime the function is executed, my system.out.println result is null. I have tried changing from @PathVariable to @RequestParam, but it throws an exception, saying that no parameter was received from the request, and I have tried changing the route to '/credenciamento/busca-procedimento/{query}' but everytime query is null, and in this case the function doesn't even get executed, since there's no query in the request.


Solution

  • I figured it out what was the problem. It wasn't because of my request or anything related to select2. The problem was the way I was handling the filtering. I was trying to follow a tutorial, however it was with an array. Since in my Case I needed a list, I tried to adapt it but with no success. I just removed all that filtering logic and filtered manually, iterating over my list and adding in my return only the procedures which had in their description the query string. PS: There's no need to @PathVariable, the correct way is with @RequestParam and the route should be the same way. With no /{q} in the end.