0

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

3
  • What does print_r(array_values($zutatName)); print? Commented Jul 6, 2015 at 18:36
  • Using the code sample above, I am receiving correct JS. Commented Jul 6, 2015 at 18:42
  • This was just a check for my self to have a look if the sql part worked well. Commented Jul 6, 2015 at 18:42

1 Answer 1

1

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.

3
  • Well this ';' error keeps popping up. Do you have a idea what could cause it? Commented Jul 6, 2015 at 18:47
  • no idea. you've already intialized $zutatName to an empty array. even if your query returned nothing or failed utterly, at bare minimum your as-posted code should have produced var zutatenArray = [[]];, which again is valid javascript: an array containing an empty array. Commented Jul 6, 2015 at 18:50
  • I've changed the name of the javascript array, now Iget this message: Uncaught SyntaxError: Unexpected token ; Commented Jul 6, 2015 at 18:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.