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?
topicsjsonis an array of objects. The default string representation of objects is[object Object]. Since you are usingdocument.write, all elements of the array are converted to strings. If you want to inspect the variable, then use the console andconsole.log. There is nothing wrong with your data, just the way you look at it.