Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
});

});

share|improve this question
    
try with double quotes around the <?php ... –  Royal Bg Apr 21 '13 at 15:53
1  
So what is your problem? –  Musa Apr 21 '13 at 15:56
    
I think you need a semicolon after your echo like that: var ingredients = <?php echo json_encode($this->ingredientsHistory); ?>; –  Marcel Gwerder Apr 21 '13 at 16:06
    
Insepct your javascript, how does the output of your json encoded array look like? –  Marcel Gwerder Apr 21 '13 at 16:47
add comment

3 Answers

up vote 2 down vote accepted

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.

share|improve this answer
    
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! –  Luke Apr 21 '13 at 17:26
    
You still can iterate it in JS the same way, will edit my post then :) –  Mathieu Amiot Apr 21 '13 at 17:30
add comment
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.

share|improve this answer
    
Isn't this what the OP is already doing? –  millimoose Apr 21 '13 at 15:56
    
Making it a string just gives you more work to do. –  Musa Apr 21 '13 at 15:57
    
I'm already doing this and it's not working? –  Luke Apr 21 '13 at 16:10
    
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? –  Marcel Gwerder Apr 21 '13 at 16:12
    
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. –  Luke Apr 21 '13 at 16:18
show 2 more comments

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>
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.