alim1990
alim1990

Reputation: 4972

jQuery autocomplete is showing empty results

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:

enter image description here

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

enter image description here

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

Upvotes: 0

Views: 894

Answers (4)

Naveen DA
Naveen DA

Reputation: 4380

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";

Upvotes: 0

Sahil Patel
Sahil Patel

Reputation: 1600

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.

Upvotes: 1

Jigar Shah
Jigar Shah

Reputation: 6223

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

Upvotes: 1

Wordica
Wordica

Reputation: 2597

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

Upvotes: 1

Related Questions