尝试使用typeahead.js和php和Ajax获取ID和值

时间:2019-01-03 08:10:44

标签: php jquery autocomplete typeahead.js

我正在尝试从数据库中获取国家的ID和名称并进行自动填充,这将获得该国家的ID以便在db中进行进一步的搜索。但是当我想要获得名称时,它只能完美地起作用,但是当我想要获取ID以及没有任何作用。非常感谢您的帮助。

fetch.php

<?php 
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
echo 'Connect Error (' . $conn->connect_errno . ') '
    . $conn->connect_error;
}
// $conn;
$request = mysqli_real_escape_string($conn,$_POST["query"]);
$sql = "SELECT * FROM countries where name like '".$request."%' ";
$result = $conn->query($sql);

$data = array();

if ($result->num_rows > 0) {
 // output data of each row
 while($row = $result->fetch_assoc()) {
      $data[] = array('name' => $row["name"] , 'id'=> $row["id"]);
 }
echo json_encode($data);
} 
?>

index.php

<script>
$(document).ready(function(){
 
 $('#country').typeahead({
  source: function(query, result)
  {
   $.ajax({
    url:"fetch.php",
    method:"POST",
    data:{query:query},
    dataType:"json",
    success:function(data){
     result($.map(data, function(item){
      return {
          id:item.id,
          name:item.name
      }
     }));
    }
   })
  }
  select: function (event,ui){
     $(this).val(ui.item.name);
     $('#idc').val(ui.item.id);
     return false;
     }
 });
 
});
</script>
 <form action="" method="post">
   <input type="text" name="country" id="country" class="form-control input-lg" autocomplete="off" placeholder="Type Country Name" />
   <input type="hidden" name="idc" value="" id="idc">
   <input type="submit" value="submit">
     </form>

上面的脚本不起作用,因为我也在尝试获取ID。 但是下面的脚本有效,因为它只显示了国家名称。

<script>
$(document).ready(function(){
 
 $('#country').typeahead({
  source: function(query, result)
  {
   $.ajax({
    url:"fetch.php",
    method:"POST",
    data:{query:query},
    dataType:"json",
    success:function(data){
     result($.map(data, function(item){
      return {
          id:item.id,
          name:item.name
      }
     }));
    }
   })
  }
 });
 
});
</script>

请注意,对于上面的脚本,我只是删除了select:function(event,ui),其他都没有改变。所以我想这就是问题所在。因为即使我没有更改退货或其他任何内容,它仍然显示名称。 非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我当天解决了问题,但是我太忙了,无法在此处更新结果。 我的错误是我将jquery自动完成功能和typeahead结合在一起。 对于我想做的jQuery自动完成功能已经足够了,这是它的代码

$('#placeautocomplete').autocomplete({
          source: "fetch.php",
          select: function (event,ui){
               $(this).val(ui.item.value)
               $('#placeidautoc').val(ui.item.id);
          },
          minLength: 2,
          autoFocus :true,

     });