I’m trying to pass this associative array to JavaScript:
Array ( [0] => Array ( [topicid] => 38 [topic] => Dad ) [1] => Array ( [topicid] => 6 [topic] => What did you eat? ) [2] => Array ( [topicid] => 4 [topic] => What have you done? ) [3] => Array ( [topicid] => 43 [topic] => He ) [4] => Array ( [topicid] => 28 [topic] => I doubt it ) [5] => Array ( [topicid] => 10 [topic] => What made you feel good ) [6] => Array ( [topicid] => 12 [topic] => Say to yourself ) [7] => Array ( [topicid] => 29 [topic] => I doubt myself ) )
In PHP file:
$topicsjson=json_encode($topics);
echo "<script>var topicsjson = $topicsjson; </script>";
In JavaScript file:
document.write(topicsjson);
It gives me this result:
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Am I missing something here?
Your PHP generates JavaScript like the following:
Use two for loops to iterate over the contents of
topicsjson.Demo: jsFiddle