0

Why would javascript return an 'unexpected token <' error when integrating php inline with javascript?

Example:

var labelPts = <?php echo json_encode($label) ?>;

This example is within a .js script called from a *.php webpage

7
  • 2
    Because the PHP would have to be processed on the server. Browsers don't know anything about PHP.
    – Pointy
    Mar 23, 2015 at 20:58
  • 1
    Unless your server is configured to run .js files through the php interpreter, then the php code will be interpreted client side, as (incorrect) javascript
    – Steve
    Mar 23, 2015 at 20:59
  • @JoseManuelAbarcaRodríguez in a single executing echo line you don't need a semi-colon (granted it's preferred for readability but it's not required) but since it's echoing JSON he should have quotes. Mar 23, 2015 at 21:04
  • php is only executed in files that contain a php extension (i.e. .php, .phtml, .php5, etc.) since your php is not in a php file, the webserver won't execute this code. A better thing to do would be to create an AJAX request to pull that data in asynchronously from the server where php CAN be executed Mar 23, 2015 at 21:06
  • It is also possible that the JSON data comes with special characters. Mar 23, 2015 at 21:11

1 Answer 1

0

As we can read here, http://php.net/manual/en/function.json-encode.php , JSON data comes with double quotes. So JavaScript will need single quotes to display the string with JSON data. Example:

<html>
  <head>
    <title>By José Manuel Abarca Rodríguez</title>
    <script type="text/javascript">
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
?>

var txt = '<?php echo json_encode($arr); ?>'; // NOTICE THE SINGLE QUOTES!!!

function show_json () {
document.getElementById("my_div").innerHTML = txt;
}
    </script>
  </head>
  <body>

    <button onclick="show_json();">Get JSON data from server</button>
    <br/>
    <br/>
    <div id="my_div">
    </div>

  </body>
</html>

Copy-paste previous code into a textfile, save it with PHP extension and run it in your brower with localhost/filename.php. It works fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.