How to perform form search using ajax?

Asked

Viewed 247 times

1

I am implementing a web application and already have the full CRUD and search implementation. However, I want to use ajax to make the system more efficient and implement the database search using ajax. I started implementing but not running with ajax, when searching the result is overlapping what was already listed previously, as you can see below. What is wrong or missing so that ajax can do this search on my system correctly.

inserir a descrição da imagem aqui My JQ:

$(document).ready(function() {
$("#searchForm").submit(function(event) {
// Stop form from submitting normally
event.preventDefault();

// Get some values from elements on the page:
var $form = $(this),
  term = $form.find("input[name='parametroBusca']").val(),
  url = $form.attr("action");

// Send the data using post

var posting = $.post(
  url, {
      parametroBusca: term
  },
  myPostWasSuccessful,
  'html'
  );
 });
});

function myPostWasSuccessful(data, textStatus, jqXHR) {
$("#result").html(data);
}

My list of registered users:

<div class="panel panel-default">
            <div class="panel-heading">
                <button type="submit" class="btn btn-success" onclick="window.location.href='/funcionarios/formFuncionarios';"> Novo funcionário</button>
                <form id="searchForm" class="navbar-form navbar-right"><input type="text" class="form-control" name="parametroBusca" value="${parametroBusca}" placeholder="Buscar...">

                </form>
            </div>
            <div class="panel-body">
            <input type="hidden" name="funcionario.id" value="${f?.id}" />
                <ul class="list-group">
                    #{list items:funcionarios, as:'f'}
                    <li class="list-group-item">
                        <div class="checkbox" id="result">
                            <label> ${f.nome} </label>
                        <div class="pull-right action-buttons">
                            <a href="@{funcionarios.editarFuncionarios(f.id)}" class="edit"><span class="glyphicon glyphicon-pencil"> Editar</span></a> 
                            <a href="@{funcionarios.removerFuncionarios(f.id)}" class="trash" data-toggle="confirmation" data-btn-ok-label="Sim" data-btn-ok-class="btn-success"  data-btn-cancel-label="Não" data-btn-cancel-class="btn-danger" data-title="Remover funcionário" data-content="Tem certeza que deseja excluir este registro?"><span class="glyphicon glyphicon-trash" > Remover</span></a> 
                            <a href="@{funcionarios.detalhesFuncionarios(f.id)}" class="flag"><span class="glyphicon glyphicon-eye-open"> Detalhes</span></a>
                        </div>
                    </div>
                    </li>
                    #{/list}
                </ul>
            </div>

and my user listing action:

public static void listagemFuncionarios(String parametroBusca) {
    List<Funcionario> funcionarios = null;
    if (parametroBusca == null) {
        funcionarios = Funcionario.find("status != ?", Status.INATIVO).fetch();         
    } else {
        funcionarios = Funcionario.find("lower(nome) like ? or lower(funcao) like ?", "%" + parametroBusca.toLowerCase() + "%", "%" + parametroBusca.toLowerCase() + "%").fetch();
    }
    render(funcionarios, parametroBusca);
}
  • All users already appear in your list? And you’re looking for a specific user?

  • all are listing normally, so the search can list by a specific user according to his name or function, only that in the search is with this bug. In the example above I have 3 registered where the third one is called administrator, in the search I’m only catching Diego.

  • 1

    Why not use jQuery Datatable? It already does this for you. I think it will be a better and faster solution. Take a look at it: https://datatables.net/

  • Vlw by tip @EGDEV, I will try to implement now.

  • Blz. Anything to call.

  • @Edgve Master of jQuery kk sorry to bother you so much, but I’m in need of help again. Give me a hand with this Datatable https://answall.com/questions/220728/tabela-datatable-workingcorrectly

Show 1 more comment

1 answer

0


You set your ajax (post) within the Submit event of your form.

Ajax requests do not submit the form the submission is made internally by a browser native object.

So it would be right to define a function outside the scope of the Submit event and that will be invoked on a button of your form and send the post request to the backend, then treat the json response inside the callback.

EnviarPost = function(){      
    $.post('/load/mensagens', { user: 'fernando'}, function(mensagens, status){

    }
});

Take a look at this documentation jquery :

Then give me a feedback if it worked correctly.

Updating

If you do not use button you can set the ajax call (post) when the user presses the enter key of your keyboard in this way :

$(document).keypress(function(e) {
    if(e.which == 13){
       //Aqui faz a chamada do ajax 
      EnviarPost();  
    }
});

As for the return treatment of ajax I cited json but can structure the code by xml,json and even a concatenated string and work in javascript to popular your results within your form. Json is a well organized and simple way.

  • Thank you for replying @Rafael, I basing myself on this post: https://stackoverflow.com/questions/30634497/how-to-post-a-search-form-using-jquery-ajax-and-put-results-in-a-div in the case that I would be in my JQ since I do not use boot nor json

  • I added the button. In the very link you sent me, I presented the example I applied in my code

  • In vdd was missing just add the id="result" in the location where I want the result. The problem now that it’s overlapping without erasing what it was already presenting

  • In the case I just noticed it’s java up there or you’re rendering the output html. That’s not it?

  • That’s right @Rafael

  • I’m not an expert on java, but I think you should make the post request turn the output of your database query into json and then return the json to the browser and popular the html in the client browser

  • I advise to redo your question back how to treat in java this type of request will have someone with this knowledge to help you

  • to ligado Rafael

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.