When I am parsing a PHP array which is filled with data from a database to JavaScript, I get an error called unexpected token '<' . The code which selectes data from my database is:
$wagennummern = NULL;
$result = $db->query("SELECT * FROM `Wagenbuch`");
while($row = $result->fetch()){
$wagennummern = $row['Wagennummer'];
}
The code to use this data in JavaScript is:
var wagennummer = <?php echo '["' . implode('", "', $wagennummern) . '"]' ?>;
The Javascript is the line where the error occurs. Can anybody tell me why there is an error and how to fix this?
2 Answers 2
The particular error message could be caused by a combination of characters that includes a < in the data.
If you want to convert a PHP data structure to a JS data structure, the json_encode, which is compatible with JS. Don't roll your own. Any special character is likely to break your attempt.
var wagennummer = json_encode( $wagennummern );
It might also be caused by the PHP not being executed at all. This would happen if you weren't loading it from a web server, or if you put it in a file with a .js file extension instead of a .php file.
2 Comments
JSON.parse(json_encode( $wagennummern )))json_encode is compatible with JS. The generated JSON/JS is not being wrapped in quotes to make it a string literal.In addition to @Quentin's answer:
I would point out that if your query does not return any row, the variable $wagennummern will be null (first line of your code)
Trying to feed a null value into implode will generate an error, which will be display as HTML, thus creating the unexpected token '<' error.
I would suggest to initialize the $wagennummern variable to an empty array, that way it will not cause any problems if you have no rows.
Another solution would be to check for the variable being !== null
2 Comments
$wagennummer with$wagennummer = [].