I'm trying to pass a PHP array to my view, and then use that array to populate jQuery autocomplete.
foreach ($products as $product)
{
$productsArray[] = array('label' => $product->getName() ,'id' => $product->getId() , 'value' => $product->getUrlSafeName());
}
$productsJson = json_encode($productsArray);
$productsJson
then gets passed to the view, where I insert it into the DOM. I'm using Twig as my templating engine:
<div id="autocompleteData">{{ productsJson }}</div>
and then my jQuery:
$( document ).ready(function() {
var autocompleteData = $('#autocompleteData').text();
$('#findoffice_location').autocomplete({
source: autocompleteData,
change: function (event, ui) { } });
});
If I console.log autocompleteData, it 'looks' like a JSON object in structure, but isn't.
If I do:
var autocompleteData = [{"label":"Toybox","id":1,"value":"toybox"},{"label":"Shoe","id":2,"value":"shoe"},{"label":"Eggs","id":3,"value":"eggs"}];
and then consolelog , each autocompleteData product is a proper JSON object, and autocomplete works as expected.