0

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

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.

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

2 Comments

hmm doesnt you need to parse it too? like JSON.parse(json_encode( $wagennummern )))
@Ifaruki — No. As I said, json_encode is compatible with JS. The generated JSON/JS is not being wrapped in quotes to make it a string literal.
1

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

What would you suggest to initialize $wagennummer with
An empty array, this would allow you to have consistent logic. So it would be $wagennummer = [].

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.