Dev Hub Dev Hub - 6 months ago 10
jQuery Question

Autocomplete issue

I am trying to display users list in

input
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);
$query->execute();

$query->bind_result($emp_number,$emp_firstname,$emp_lastname);
$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;

$query->close();


My JS Code

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

$.ajax({
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));
});
//console.log(response);
},
dataType: 'json'
});
}
}, {minLength: 3 });
});


Getting Response


[{"emp_number":1,"fname":"Arslan","lname":"Hassan"},{"emp_number":2,"fname":"Muneeb","lname":"Janjua"
},{"emp_number":3,"fname":"hr","lname":"user"}]


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>
<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">
</div>
<button type="submit" class="btn btn-primary">Genrate Report</button>
</form>

Answer

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: http://api.jqueryui.com/autocomplete/#option-source

Comments