How to not duplicate items in a list returned from json with ajax

0

I'm having problems, basically I'm doing a search on products with like, but it's duplicating the products, I'll attach an image that clarifies better.

$(document).ready(function(){
  $("#search").on( 'keyup', function () {

    var pesquisa = $("#search").val();
    if (pesquisa.length > 0) {
    $(".categorias").hide();
    $("#itempesquisa").remove();
    $.ajax({
      url:("ajax/buscaprods.php"),
      type: "POST",
      data: "busca="+pesquisa,
      success:function(dados){
        $.each(dados, function(index){
          var len    = dados.length;
          for (var i=0; i < len; i++){
            $("#listaprodutos").append("<li id='itempesquisa' class='item-content'><img src='"+dados[index].imgproduto+"' width='44'></div><div class='item-inner'><div class='item-title-row'><div class='item-title'>"+dados[index].descricao+"</div></div><div class='item-subtitle'>R$ "+dados[index].preco+"</div></div></li>")
          }
        });
      }})
    } else {
      $(".categorias.").show();
    }
  })

})

PHP     

ini_set( 'display_errors', true );
error_reporting(E_ALL & ~ E_NOTICE & ~ E_DEPRECATED);

include('../class/mysql_crud.php');

$busca = $_POST["busca"];

$db = new Database();
$db->connect();
$db->sql("SELECT * FROM cad_produtos WHERE descricao LIKE '%$busca%' ");
$res = $db->getResult();

echo json_encode($res);

    
asked by anonymous 07.07.2016 / 20:58

1 answer

1

Your problem is that it is assigning a id fixed to a dynamic element.

In the line below, as you are reporting a id , jQuery must understand that there is only one element, then it will remove only the first record.

$("#itempesquisa").remove();

however you are generating multiple elements with the same id.:

for (var i=0; i < len; i++){
  $("#listaprodutos").append("<li id='itempesquisa' class='item-content'><img src='"+dados[index].imgproduto+"' width='44'></div><div class='item-inner'><div class='item-title-row'><div class='item-title'>"+dados[index].descricao+"</div></div><div class='item-subtitle'>R$ "+dados[index].preco+"</div></div></li>")
}

An output, if you really need an id in these items, is to use the i variable of the for loop to make id unique, so you can use a common class for all elements. p>

$(".itempesquisa").remove();
.
.
.
for (var i=0; i < len; i++){
  $("#listaprodutos").append("<li id='itempesquisa_" + i + "' class='item-content itempesquisa'><img src='"+dados[index].imgproduto+"' width='44'></div><div class='item-inner'><div class='item-title-row'><div class='item-title'>"+dados[index].descricao+"</div></div><div class='item-subtitle'>R$ "+dados[index].preco+"</div></div></li>")
}
    
07.07.2016 / 21:23