Mike Traa
Mike Traa

Reputation: 31

Fill a javascript array with php variable

I want to fill a javascript array with my php variable $jaar. But when I print it in the js file I don't get the right output.

php file

<?php
$jaar = "[";
$result = mysql_query("SELECT jaar FROM agenda");
    while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
        $jaar .= "\"" . $row[0] . "\""; 
        $jaar .= ",";
    }
$jaar{ strlen($jaar)-1 } = ']';

echo "<script type='text/javascript'>var db_jaar = '" . $jaar ."'</script>";

?>
<script src="js/calender.js"></script>

js file

//Get the variable from the php file
alert(db_jaar);
//printed: ["2018","2018"]

//When I make the variable local
var db_jaar = ["2018","2018"];
alert(db_jaar);
//printed: 2018,2018 <-- This is what I want

Upvotes: 3

Views: 1109

Answers (1)

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

Some changes required:

while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
    // create $jaar[]
    $jaar[] = $row[0];
}
// echo using json_encode
?><script type='text/javascript'>var db_jaar = <?php echo json_encode($jaar); ?>;</script>";<?php

Read more:

Upvotes: 6

Related Questions