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
4
  • 3
    Try to use json_encode and json_decode. And use ajax request. Commented Jan 31, 2018 at 13:28
  • 1
    this is a string not an array. you are appending it to a string, which you think you are making Commented Jan 31, 2018 at 13:28
  • var db_jaar = ' <-- here single quote is creating string variable, remove it and it will be array as required. Commented Jan 31, 2018 at 13:31
  • 1
    The mysql PHP extension is dead -- Stop using the mysql_*() PHP functions. They are old, deprecated since PHP 5.5 and completely removed in PHP 7. Use mysqli or PDO_mysql instead. Read the answers to this question to learn more about why and how. Commented Jan 31, 2018 at 13:36

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

Comments

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.