0

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.

3
  • What's the output of console.log(autocompleteData) in the JS? Commented Oct 2, 2013 at 10:29
  • [{"label":"Toybox","id":1,"value":"toybox"},{"label":"Shoe","id":2,"value":"shoe"},{"label":"Eggs","id":3,"value":"eggs"}] Commented Oct 2, 2013 at 10:31
  • and if I manually enter that in the js as per my last code block in my question, console.logging gives me [Object,Object,Object] and autocomplete works. Commented Oct 2, 2013 at 10:33

2 Answers 2

1

You need to convert the string output of .text() to JSON:

source: jQuery.parseJSON(autocompleteData)

When you enter it manually, you're feeding in actual JSON, hence why it works.

Sign up to request clarification or add additional context in comments.

Comments

0

Try and wrap autocompleteData in a call to $.parseJON like this:

$( document ).ready(function() {

    var autocompleteData = $('#autocompleteData').text();       

    $('#findoffice_location').autocomplete({ 
        source: $.parseJON(autocompleteData),
        change: function (event, ui) {  } });

});

Edit @George beat me to it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.