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
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.
.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