Reputation: 43
I'd like to show some data of my database with Javascript. Here's my PHP script:
$arrayDatabase = array();
$statement = $link->prepare("SELECT project.ID, project.titel, project.subtitel, project.plaatje, project.beschrijving, project.link FROM project" );
$statement->execute();
$statement->bind_result($ID, $titel, $subtitel, $plaatje, $beschrijving, $site);
while($statement->fetch()){
echo '
<div class="singleProject" id="'.$ID.'">
<img src="'.$plaatje.'" alt="'.$titel.'" />
<div>
<h2>'.$titel.'</h2>
<div><p>'.$subtitel.'</p></div>
</div>
</div>
';
$arrayRij= array($ID, $beschrijving, $site);
array_push($arrayDatabase, $arrayRij);
}
$statement->close();
But if I use json_encode to get the array to Javascript, it won't work.
var jsArray = <? echo json_encode($arrayDatabase); ?>;
EDIT: In my browser there is only a ';' after var jsArray =
The weird thing is. If a use a multidimensional array on my own like:
$phpArray = array(array("foo", "bar"), array("foo", "bar"));
My script works.
Upvotes: 0
Views: 74
Reputation: 6349
You can get the JSON data/object from php to javascript like this.
$arr = json_encode($arrayDatabase);
echo <<<END
<script type="text/javascript">
var jsArray = $arr;
</script>
END;
Upvotes: 0
Reputation: 1718
Although i also think you should go the AJAX way (or do whatever you are trying to do in php and output the final html instead of doing stuff in js), you can fix your current problem this way:
json_encode returns a string not a javascript object, so you need to parse that in js to get the real object:
var jsArray = JSON.parse("<? echo json_encode($arrayDatabase); ?>");
note that you may need to use a JSON polyfill for this to work in old ie versions. Also you may need to escape quotes in the string returned from json_encode.
Upvotes: 1