Reputation: 15
I want to transform a php array into a javascript array.
When I try this code:
<?php
//db data
$verbindung = new mysqli($host_name, $user_name , $password, $database);
if ($mysqli->error) {
die('Verbindung schlug fehl:');
}
$sql= "SELECT Name FROM Zutaten;";
$result = mysqli_query($verbindung, $sql);
$zutatName = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$zutatName[] = $row['Name'];
}
print_r(array_values($zutatName));
?>
<script>
var zutatenArray = <?php echo json_encode($zutatName); ?>;
</script>
I get the following error messeage: "SyntaxError: expected expression, got ';' var zutatenArray = ;"
When I use this code:
<?php
//db data
$verbindung = new mysqli($host_name, $user_name , $password, $database);
if ($mysqli->error) {
die('Verbindung schlug fehl:');
}
$sql= "SELECT Name FROM Zutaten;";
$result = mysqli_query($verbindung, $sql);
$zutatName = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$zutatName[] = $row['Name'];
}
print_r(array_values($zutatName));
?>
<script>
var zutatenArray = [<?php echo json_encode($zutatName); ?>];
</script>
Then there is an empty javascript array. What am I missing?
Best regardds
Upvotes: 0
Views: 284
Reputation: 360922
Your array braces are unecessary:
var zutatenArray = [<?php echo json_encode($zutatName); ?>];
^--------------------------------------^
as they would be added already by json_encode()
. Given that your error message says zutatenArray = ;
, your posted code is NOT what is producing this error.
Even if json_encode() failed utterly and returned a boolean false, the generated Javascript would've looked like
var zutatenArray = [];
which is perfectly legitimate.
Upvotes: 1