3

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
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
Mike Traa
  • 31
  • 7
  • 3
    Try to use json_encode and json_decode. And use ajax request. – Victor Sitnic Jan 31 '18 at 13:28
  • 1
    this is a string not an array. you are appending it to a string, which you think you are making – Harshada Chavan Jan 31 '18 at 13:28
  • var db_jaar = ' <-- here single quote is creating string variable, remove it and it will be array as required. – Dharmang Jan 31 '18 at 13:31
  • 1
    **The `mysql` PHP extension is dead** -- Stop using the [`mysql_*()` PHP functions](http://php.net/manual/en/function.mysql-connect.php). They are old, deprecated since PHP 5.5 and completely removed in PHP 7. Use [`mysqli`](http://php.net/manual/en/book.mysqli.php) or [`PDO_mysql`](http://php.net/manual/en/ref.pdo-mysql.php) instead. Read the answers to [this question](https://stackoverflow.com/q/12859942/4265352) to learn more about why and how. – axiac Jan 31 '18 at 13:36

1 Answers1

6

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:

Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67