I’ll be honest, I thought this was going to be a 5 minute job to a add nice be of autocompleteness to a project. However, if the requirement to pass 3 parameters as your data array (id, value, label) was in the documentation, I missed it.
The JSON, should look like this;
{"response":"true","message":[{"value":"CSS3","label":"CSS3","id":"3"},{"value":"Slider","label":"Slider","id":"4"},{"value":"PSD","label":"PSD","id":"5"},{"value":"CSS","label":"CSS","id":"7"}]}
I was using CodeIngiter, so my controller looks like this (ignoring the DB selects which should be moved to a model). Also, ensure that you output the correct headers (application/json), otherwise you’ll just be setting yourself up for a whole load of new, difficult to spot problems;
function get_tags_as_json()
{
$tag = $_REQUEST['term']; //get term parameter sent via text field.
$this->db->select('*');
$this->db->from('tags');
$this->db->like('tag', $tag);
$this->db->limit('5');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
$data['response'] = 'true';
$data['message'] = array();
foreach ($query->result() as $row)
{
$data['message'][] = array(
'value' => $row->tag,
'label' => $row->tag,
'id' => $row->id
);
}
}
else
{
$data['response'] = 'false';
}
header("Content-type: application/json");
echo json_encode($data);
}
and then my jQuery;
$(function() {
$( "#tags" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://linkspro.dev/admin/get_tags_as_json",
dataType: "json",
data: request,
success: function(data){
if(data.response == 'true') {
response(data.message);
}
}
});
},
minLength: 1
});
});