jQuery autocomplete is showing empty results

Deadly 提交于 2019-12-08 11:14:43

问题


I have this PHP script to get all patient name from my database:

<?php

error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once('connection.php');
header("Content-type:application/json");
$cid = $_SESSION['clinic_id'];

$res = array();
$getPatients = "SELECT * FROM patient WHERE clinic_id = :cid  ORDER BY patient_id DESC";

$execGetPatients = $conn->prepare($getPatients);
$execGetPatients->bindValue(':cid', $cid);
$execGetPatients->execute();
$getPatientsResult = $execGetPatients->fetchAll();

$i = 0;
foreach($getPatientsResult as $result)
{
    $res[$i] = $result;
    $i++;
}

echo json_encode($res);
?>

And I have a text box where I want to display the patient_name as autocomplete using jquery-ui autocomplete library.

Here is my jQuery script:

  $(document).ready(function()
  {
    $( "#searchTxt" ).autocomplete({
      source: "../php/autoComplete.php"
    });
  })

I can see that if a type a name at the network tab I can see a returned array:

But at the text box I see that the autocomplete are empty like in the following image:

And it is showing 2 white boxes instead of one that of the returned array


回答1:


This is nice plugin for that kind of results: https://twitter.github.io/typeahead.js/




回答2:


I think its because the data you have passed, it seems there are multiple columns, you need to specify label and value or it should be simple array (as per your code it should be this kind of data)like

var availableTags = [
  "ActionScript",
  "COBOL",
  "ColdFusion",

];

You can check more about custom field passing




回答3:


Twitter typeahead.js is the best option to implement this feature.

Please take a look into this to achieve it with PHP, AJAX, and TypeAhead.js

<script>
$(function() {
  $("#searchTxt").typeahead({
    source: function(query, process) {
      var textVal=$("#searchTxt").val();
      $.ajax({
        url: '/php/autoComplete.php', // Please add full URL here
        type: 'POST',
        data: 'term=' + textVal,
        dataType: 'JSON',
        async: true,
        success: function(data) {
          process(data);
          console.log(textVal);
        }
      });
    }
  });
});
</script>

link to TypeAhead.js

Let me know if you need any help.




回答4:


Because you need label and value filed in your json array so your sql would be,

$getPatients = "SELECT *, name as label, id as value FROM patient WHERE clinic_id = :cid  ORDER BY patient_id DESC";


来源:https://stackoverflow.com/questions/44940474/jquery-autocomplete-is-showing-empty-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!