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.
-
Try testing the javascript in a separate script and use an ajax call to get the json.insanityCode– insanityCode2014年02月12日 17:52:42 +00:00Commented Feb 12, 2014 at 17:52
-
Please provide a better problem description than "it won't work". Give us some useful information.Felix Kling– Felix Kling2014年02月12日 18:15:04 +00:00Commented Feb 12, 2014 at 18:15
2 Answers 2
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.
2 Comments
json_encode returns a sting indeed, but it is directly injected in the JS source code, so it will be interpreted as JS array or object literal. There is no need for JSON.parse.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;