calzone calzone - 1 month ago 10
jQuery Question

jquery autocomplete over ajax fails under CakePHP3.x

I have a page with the following jQuery snippet:

$( "#fuser" ).autocomplete({
source: "/users/jsonusers",

select: function(event, ui) {
$("#find").val(ui.item.value);
return false;
},
focus: function(event, ui) {
$("#find").val(ui.item.label);
return false;
}


The code at the "source url" looks like this:

$connection = ConnectionManager::get('default');
$results = $connection->execute($query, ['str' => $find])->fetchAll('assoc');

$users = [];
foreach($results as $user){
$users[] = ['value'=>$user['user_id'], 'label'=>$user['full_name']];
}

$this->set(compact('users'));
// $this->set('_serialize', 'users'); // this is the correction that works
$this->set('_serialize', ['users']); // this is Bake's default


When I try to use the autocomplete widget, it fails completely.

Looking in my console, I think I know why. It looks like Cake is putting my "keys" ('name' and 'value') into quotes, so the json looks like this:

[
{
"value": "46",
"label": "Test User"
}
]


Instead of like this:

[
{
value:"46",
label:"Test User"
}
]


So I figured, "just build the damn object yourself manually. Easy to iterate though the array and format the json as desired, no?"

But no, I would be wrong. CakePHP does not allow me to dictate at all how data is transmitted over ajax. I am stuck with Cake's formatting. If I try to make my own json object, it gets mangled with encoding and STILL gets buried as a sub-object regardless.

What am I doing wrong? Or is this just a bug with Cake? If so, is there some workaround? Can I get jQuery autocomplete to work with the json object returned by Cake? Do I need to parse it further in the js? Sadly, if so, that exceeds my knowledge of using jQuery.

Any help is much appreciated.

Answer

If you really need array like this:

[
  {
    value:"46",
    label:"Test User"
  }
]

Then you can simply do:

$this->set('_serialize', 'users');

Instead of:

$this->set('_serialize', ['users']);

Means just serialize the string not an array.

Comments