Dev Hub Dev Hub - 1 year ago 60
jQuery Question

Autocomplete issue

I am trying to display users list in

field with jquery auto-complete function. I facing issue in displaying name and n selection update value to field.

My PHP Code:

include '../_db.php';

// get what user typed in autocomplete input
$name = trim($_GET['name']);

$param = "%{$name}%";
$query = $conn->prepare('SELECT emp_number, emp_firstname, emp_lastname FROM `hs_hr_employee` WHERE emp_firstname LIKE ? OR emp_lastname LIKE ? ');
$query->bind_param('ss', $param,$param);

$a_json = array();
$a_json_row = array();

while( $query->fetch() )
$a_json_row["emp_number"] = $emp_number;
$a_json_row["fname"] = $emp_firstname;
$a_json_row["lname"] = $emp_lastname;
array_push($a_json, $a_json_row);

$json = json_encode($a_json);
print $json;


My JS Code

$( "#search-emp" ).autocomplete(
source: function (request, response)
var form_data = {
ajax : '1',
name : $("#search-emp").val(),
actioncall : 'search-emp'

type: "POST",
url: "_ajax.php",
data: form_data,
success: function(response)
$.each( response, function( key, value )
//alert( key + ": " + value );
console.log('element at index ' + key + ' is ' + JSON.parse(value));
dataType: 'json'
}, {minLength: 3 });

Getting Response


MY HTML code

<form class="form-inline">
<div class="form-group">
<label for="exampleInputName2">Employee Name: </label>
<input id="search-emp" type="text" class="form-control" placeholder="*">
<div class="form-group">
<label for="exampleInputEmail2">Date Range: </label>
<input type="text" class="form-control" id="dp-from" placeholder="From">
<input type="text" class="form-control" id="dp-to" placeholder="To">
<button type="submit" class="btn btn-primary">Genrate Report</button>

Answer Source

The problem it's because jQuery auto-complete wants to have 2 fields named label and value. The content from label will be displayed in the auto-complete.

Because your server return other name for the keys you have 2 options:

  1. Change the server to return a json like:

    [{"emp_number":1,"fname":"Arslan","lname":"Hassan", "label":"Arslan Hassan", "value": "Arslan Hassan"},....]

  2. Or on the success callback from ajax create an array with this fields (label and value) and pass this array to response() callback.

You can find more informations here: