Sunday, 8 September 2013

Using PHP array for jQuery autocomplete

Using PHP array for jQuery autocomplete

I have a list of guests that I want to be able to use in the jQuery
autocomplete but I can't seem to get the format correct. I'm using CakePHP
2.3.8 and have a list of guests sent from my controller to view. When I
type into the text box, I get the following error
//in reference to source of the elements to populate the autocomplete list
Property 'source' of object [object Object] is not a function
I searched for this error on here, but I couldn't find anything related to
converting a PHP array while also accounting for the index number of that
item. I have a PHP array in the format of
echo "<pre>"; print_r($guests); echo "</pre>";
//results in the following, where the index is the guest's ID
array(
[1] => guest a,
[2] => guest b,
[3] => guest c
)
I used json_encode to convert the php $guests array which results in the
following format
var guests = {"1":"guest a","2":"guest b","3":"guest c"};
I noticed in the documentation the source of the data is usually in a
format like
var guests = [guest_a, guest_b, guest_c];
Keep in mind index refers to the guest's ID, so I need to use this number
to make sure the correct guest is chosen, if there happens to be two
guests with the same name
So, here's the javascript/jquery for the autocomplete box
var guests = <?php echo json_encode($guest_list); ?>;
$(function() {
$( "#guests_autocomplete" ).autocomplete({
source: guests
});
});
How can I properly format my guests array to work with autoComplete and
still keep track of the guest's id?

No comments:

Post a Comment