I need to pass a parameter from PHP to JavaScript, so I do this:
var title='<?php echo ($home->title); ?>';
console.log(title);
but I obtain
Uncaught SyntaxError: Invalid or unexpected token
Can anyone help me?
This is the output:
var titolo_it='<p><strong>ddddddddddd</strong></p>
';
The line break in $home->title
is breaking the JavaScript syntax. You cannot include a literal line break in a JavaScript string that way.
To fix this, you need to be sure the data is properly encoded, so any apostrophes, line breaks, etc. are in proper format for JavaScript. Use the built-in function json_encode()
, like this:
var title=<?php echo json_encode($home->title); ?>;
console.log(title);