PHP Echo Into Javascript = Syntax Error: Expected Expression, Got '<'

- 1 answer

Despite a mountain of posts on the subject, I'm having no luck getting embedded php to echo out into a JS variable. Even stripped down to:

//PHP from app.php
$data = json_encode(5);

//and JS in results.html
var data = <?php echo $data; ?>;

console.log only produces "SyntaxError: expected expression, got '<'". With quotes around the

It seems that the PHP isn't parsing. As Ed Cottrell points out below, there's a here remains unpopular and unanswered. I ran the test.php created by pemcconnell and that works for me. He says that suggests "another problem with your JS" but my JS is working just fine otherwise.

So... I throw myself to the wolves. What stupid thing am I doing? If anyone can help I will make an altar in their honor, complete with garlands and incense.



I'm still unable to do any variation on php echo but I switched to Twig's {{ }} and it works. I had to put quotes around my entire "JSON.parse()" statement (I got desperate) to figure out that Twig WAS parsing, but was messing up the JSON by auto-escaping double-quotes. Once I fixed that with {{ myData.json_encode()|raw }} it was perfect.

As for the original issue, Idunno. My htaccess is set to recognize html docs as php. I also tried changing results.html to .php, and a million other things I've read here and there. It "should" work but it don't.

Thanks, everyone, for the feedback. It was all good advice and helped me figure things out.