Autocomplete does not work with jquery php mysql

0

This is the code I have:

$(document).ready(function() {
  //Al escribr dentro del input con id="pieza"
  $('#pieza').keypress(function() {
    //Obtenemos el value del input
    var pieza = $(this).val();
    var dataString = 'pieza=' + pieza;

    //Le pasamos el valor del input al ajax
    $.ajax({
      type: "POST",
      url: "autocomplete.php",
      data: dataString,
      success: function(data) {
        //Escribimos las sugerencias que nos manda la consulta
        $('#suggestions').fadeIn(1000).html(data);
        //Al hacer click en algua de las sugerencias
        $('.suggest-element').live('click', function() {
          //Obtenemos la id unica de la sugerencia pulsada
          var id = $(this).attr('id');
          //Editamos el valor del input con data de la sugerencia pulsada
          $('#pieza').val($('#' + id).attr('data'));
          //Hacemos desaparecer el resto de sugerencias
          $('#suggestions').fadeOut(1000);
        });
      }
    });
  });
});
.suggest-element {
  margin-left: 5px;
  margin-top: 5px;
  width: 350px;
  cursor: pointer;
}
#suggestions {
  width: 350px;
  height: 150px;
  overflow: auto;
}
<form>
  <input type="text" size="50" id="pieza" name="pieza" />
  <div id="suggestions"></div>
</form>
<?php $search=$ _POST[ 'pieza']; $query=$ db->query("SELECT nombre FROM piezas WHERE nombre like '" . $search . "%'" );
while ($row = $query->fetch_assoc()) { 
echo '
<div class="suggest-element">'.$row['nombre'].'</div>'; 
} ?>
The result of this is the following:

He shows me the two registers and will not let me search or autocomplete ...

    
asked by Pavlo B. 17.01.2017 в 18:14
source

1 answer

1

The first thing and even though it has nothing to do with it is a bit dangerous, the use of POST or GET variables without cleaning in query chains to the database, can make SQL INJECTION.

Could your problem be that you are not passing on the suggestion ID?

<div class="suggest-element">'.$row['nombre'].'</div>'; 

Are you missing something like this, right?

<div id="'.$row['id'].'" class="suggest-element">'.$row['nombre'].'</div>'; 

Because you say

 //Obtenemos la id unica de la sugerencia pulsada
 var id = $(this).attr('id');

But do not set the ID ever.

    
answered by 22.02.2017 / 18:48
source