show a result in ajax in real time

0

I have this code and the problem that I present is that if I write a word several times and the word is available in the database it shows me the result as many times as the letters have the word.

For example if I search for "stack" and it is available it would appear Stack it five times and ideally it will show it only once.

<section class="Search">
        <article class="Search-bar">
            <span class="input-group-addon" id="sizing-addon1"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></span>
            <input type="text" class="Search-input" placeholder="Buscar hechizo, ej: Expelliarmus" aria-describedby="sizing-addon1" id="busqueda">
        </article>
        <div id="resultados" class="Search-resultados"></div>

        <script>
            $('#busqueda').keyup(function(e){
                $("#resultados").text("");
                consulta = $("#busqueda").val();
                 $.ajax({
                 data: {'name': consulta},
                 url: '/buscar/',
                 type: 'get',
                 success : function(data) {                     
                        for (i=0;i<data.length;i++){

                            if((i % 2)==0)
                                $("#resultados").append("<a class=\"Search-resultados--item \" href=/"+data[i].slug+">"+data[i].name+"</a>");
                            else
                                $("#resultados").append("<a class=\"Search-resultados--item Search-resultados--info\" href=/"+data[i].slug+">"+data[i].name+"</a>");
                        }
                        if(consulta == ""){$("#resultados").text("");}
                 },
                 error : function(message) {
                         $("#resultados").text("");
                      }
                 });
            });
        </script>
    </section>

If anyone could help me with this, I would appreciate it. Greetings!

    
asked by ikenshu 14.09.2016 в 19:48
source

1 answer

1

We have already fixed it. In case someone serves you, we have put the following:

$("#resultados").text("");

just before the for

    
answered by 14.09.2016 / 20:03
source