Clear table body before being popular again with Jquery and Ajax

1

I have the following function:

$("#numeroRequisicao").change(function() {
    var numeroRequisicao = $(this).val();
    $.ajax({
        type: "POST",
        url: "../controller/ajax.selectItemRequisicaoPesquisar.php?numeroRequisicao="+numeroRequisicao,
        dataType: "JSON",
        success: function(res) {
            for(var i=0; i<res.length; i++)
            {
                $("#tab_logic").append('<tr class="text-center"><td>'+i+'</td><td>'+res[i].nome_GAThemocomponente+'</td><td>'+res[i].qtd_GATitemRequisicao+'</td><td>'+res[i].frequencia_GATitemRequisicao+'</td><td>'+res[i].cirurgia_GATitemRequisicao+'</td></tr>');
            }
        }
    });
});

And the following table in HTML:

<table class="table table-bordered table-striped" id="tab_logic">
    <thead> 
        <tr>
            <th class="text-center" style="width: 5%;">Indice</th>
            <th class="text-center" style="width: 25%;">Hemocomponente</th>
            <th class="text-center" style="width: 15%;">Quantidade</th>
            <th class="text-center">Frequência (Aviso)</th>
            <th class="text-center">Cirurgia (Aviso)</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

When the user clicks the btnPesquisar button, the Ajax function will be triggered, it will pick up the items and fill in the table, it is working correctly, the problem is:

If the user chooses the code request 1 and clicks the btnPesquisar button, he / she will fill the table with the items of the code 1 request, however if the user does not refresh the page and wants to see the code request 2 , the items of the requisition of code 2 will be added in the table without it being cleaned, thus, the items of the previously seen requisition together with those of the requisition seen at the moment.

How can I clean the table before filling in the new data?

    
asked by anonymous 17.09.2017 / 16:02

1 answer

1

Generate a string with everything so you can delete everything at once:

success: function(res) {
    var html = res.reduce(function(string, obj, i) {
      return string + '<tr class="text-center"><td>' + i + '</td><td>' + obj.nome_GAThemocomponente + '</td><td>' + obj.qtd_GATitemRequisicao + '</td><td>' + obj.frequencia_GATitemRequisicao + '</td><td>' + obj.cirurgia_GATitemRequisicao + '</td></tr>'
    }, '');
    $("#tab_logic tbody").html(html);
}
    
17.09.2017 / 16:17