Galera é o seguinte, estou elaborando um método de pesquisa utilizando o ajax e jquery para requisição, porém, quando clico no botão “pesquisar” nada acontece. Gostaria de saber no que estou errando, segue abaixo minha view (html) e meu controller.
View html
<div class="row">
<div class="form-group col-md-8 offset-2">
<label for="txt-pesquisa">Instituição a ser Pesquisada:</label>
<input class="form-control" id="txtSearch">
<button style="margin: 10px;" type="button" class="btn btn-info" id="btn-search">Pesquisar</button>
</div>
</div>
<table class="table table-dark table-striped table-bordered" id="tbl">
<thead>
<th scope="col">#</th>
<th scope="col">Nome da Instituição</th>
<th scope="col">Endereço</th>
<th scope="col">Ações</th>
</thead>
<tbody>
<tr th:each="instituicao : ${instituicoes}">
<td th:text="${instituicao.id}"></td>
<td th:text="${instituicao.nome}"></td>
<td th:text="${instituicao.endereco}"></td>
<td>
<a style="color: #fff;" class="btn btn-info" th:href="@{/instituicoes/editar/{id}(id=${instituicao.id})}">Editar</a> |
<a style="color: #fff;" class="btn btn-danger" th:href="@{/instituicoes/excluir/{id}(id=${instituicao.id})}">Excluir</a>
</td>
</tr>
</tbody>
</table>
</div>
<div th:replace="fragmentos/fragmentos :: footer"></div>
<script src="/webjars/jquery/3.4.1/jquery.min.js"></script>
<script src="/webjars/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#btn-search').click(function(){
$.ajax({
method: 'GET',
url: '/instituicoes/searchPorNome/' + $('#txtSearch').val(),
success: function(data){
$('#tbl tbody > tr').remove();
$.each(data, function(){
$('#tbl tbody').append(
'<tr>' +
'<td>' + this.nome + '</td>' +
'<td>' + this.endereco + '</td>' +
'<td>' +
' <a href="/instituicoes/editar/' + this.id '">Editar</a> | ' +
' <a href="/instituicoes/excluir/' + this.id '">Excluir</a> ' +
'</td>' +
'</tr>'
);
});
},
error: function({
alert('Não foi possível executar a pesquisa');
});
});
});
});
</script>
Controller
@GetMapping({"/searchPorNome/{nome}", "/search"})
public @ResponseBody List<Instituicao> searchPorNome(@PathVariable Optional<String> nome){
if(nome.isPresent()) {
return repositorioInstituicao.findByNomeContaining(nome.get());
}else{
return repositorioInstituicao.findAll();
}
}