1

I have an array of items from the database.

`$this->ingredientsHistory` is the variable that contains the array.

I want to convert this into a javascript var that will hold them all and I can then use them in the autocomplete jquery UI function.

I've tried var ingredients = <?php echo json_encode($this->ingredientsHistory); ?>

This is an example of a print_r($this->ingredientsHistory); output...

Array ( [0] => Array ( [name] => oranges ) [1] => Array ( [name] => chicken ) )

Any help would be appreciated.

Edit - more information:

$(function() {
var ingredients = <?php echo json_encode($this->ingredientsHistory); ?>;
console.log(ingredients);
//this is the default tags that jquery gives me - i need to turn ingredients into something similar.
var availableTags = [
  "ActionScript",
  "AppleScript",
  "Asp",
  "BASIC",
  "C",
  "C++",
  "Clojure",
  "COBOL",
  "ColdFusion",
  "Erlang",
  "Fortran",
  "Groovy",
  "Haskell",
  "Java",
  "JavaScript",
  "Lisp",
  "Perl",
  "PHP",
  "Python",
  "Ruby",
  "Scala",
  "Scheme"
];
$( "#tags" ).autocomplete({
  source: ingredients
});

});

4
  • try with double quotes around the <?php ... Commented Apr 21, 2013 at 15:53
  • 1
    So what is your problem? Commented Apr 21, 2013 at 15:56
  • I think you need a semicolon after your echo like that: var ingredients = <?php echo json_encode($this->ingredientsHistory); ?>; Commented Apr 21, 2013 at 16:06
  • Insepct your javascript, how does the output of your json encoded array look like? Commented Apr 21, 2013 at 16:47

3 Answers 3

2

Your problem is that you must extract each name property from your php array.

Use something like this

<?php

$ingredientsArray = array(
    array('name' => "Lettuce"),
    array('name' => "Butter"),
    array('name' => "Chocolate"),
    array('name' => "Cheese"),
); // This is your original data structure

$resultArray = array(); // Let's treat it to get a plain array of ingredient names
foreach ($ingredientsArray as $ingredient)
    $resultArray[] = $ingredient['name'];

// And finally, output it
echo json_encode($resultArray);

And if you really want to get it in JS-only (though I don't recommend it, in case you have sensitive data in your $ingredientsArray variable

$(function() {
    // Your PHP-to-JSON stuff
    var ingredientsArray = <?php echo json_encode($ingredientsArray); ?>;

    var ingredientNames = []; // There are faster ways such as reduce, but it's the most browser-compatible way to do this.
    for (int i = 0, l = ingredientsArray.length; i < l; ++i)
        ingredientNames.push(ingredientsArray[i]['name']);

    // Then assign it to your autocomplete plugin
    $('#tags').autocomplete({ source: ingredientNames });
});

Note that hasOwnProperty hasn't been used as we already know the data format for the array.

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

2 Comments

Perfect, I knew I was dealing with a multi dimensional array which is why I posted the code so indepth. I wasn't sure if there was a javascript way of getting within the arrays! This works a treat though, thanks!
You still can iterate it in JS the same way, will edit my post then :)
1
echo json_encode($this->ingredientsHistory);

Use JSON as a way to communicate with the client. Simple, fast, widely supported, etc. Couldn't be more easy. And in the client(JavaScript), you have JSON.stringify and JSON.parse to deal with this.

Native supported is unreliable and not guaranteed in legacy mode, but you can use the OFFICIAL JSON implementation to guarantee cross-browser support for JSON. If you are using jQuery, as you indicated, you won't have a problem, just use the jQuery methods instead.

Also, in PHP5, you can use

var ingredients = "<?= $this->ingredients; ?>";

If the inline processing fails, you can always simply use Ajax for this.

$.ajax({
    url: "blabla",
    data: "blabla",
    type: "POST",
    dataType: "json",
    success: function(serverResponse) {
        console.log(serverResponse);
    }
});

And echo json_encode(whatever) on the Ajax target url.

4 Comments

Have you tried adding the semicolon missing in your code as stated in my comment above? And the question is what is not working? Any errors in the console? How are you trying to access the elements?
I've added the semi colon and I have this code - var ingredients = <?php echo json_encode($this->ingredientsHistory); ?>; console.log(ingredients); In the console, I'm getting object over and over.
@alex22, what you can do in PHP5? You mean short tag notation for echo statement? In prior versions it will work only if short_open_tag option is enabled, after 5.4 it's always available.
I've changed the question to add more information of how I need to information to store in the var.
0

You can do a PHP iteration to push elements into Array.

<script>
var jsArray = new Array();
<?php
   for ($this->ingredientsHistory as $value) 
?>
jsArray.push(<?=$value?>);
<?php
   } 
?>
</script>

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.