This question already has an answer here:
I have a question about using a php variable in my javascript file. This is my index.php file:
<body>
<div class="container">
<div class="row">
<div class="span12">
<?php
if(isset($_GET['appid'])) {
// GET appid
$appid = $_GET['appid'];
$json_url ='http://api.url.com/api/gateway/call/1.4/getApp?appid=' . $appid;
$ch = curl_init($json_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$str = curl_exec($ch);
curl_close($ch);
$data = json_decode($str);
$array = json_encode($data);
}
else{
}
?>
<p id="errors" class="text-error"></p>
</div>
</div>
<hr>
</div> <!-- /container -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/plugins.js"></script>
<script src="js/main.js.php"></script>
</body>
As you can see I check if an appid is sent. When I received it I load data from an api. In the bottom of the page I have a link to my javascript file. (.php because I want to use the php var $ array in my js file)
My main.js.php:
$(document).ready(function() {
var data = <?php echo $array;?>;
alert(data);
});
But I got always error in console:
Uncaught SyntaxError: Unexpected token <
Does anyone know what I do wrong?
</div>
You are creating the array in a completely different file! The two variables are not in the same scope. What's more, the Javascript file is apparently not interpreted as PHP (and neither should it). So:
<?
tag, which it should never see.$array
variable in main.js.php
.Start by understanding how Javascript and PHP are interpreted, see Reference: Why does the PHP code in my Javascript not work?.
Try this,
$(document).ready(function() {
var data = '<?php echo isset($array) ? $array :
json_encode(array("nothing in array data"));?>';
// if $array not set then it should return {"0":"nothing in array data"}
alert(data);
});
you forgot to Quote Value of var data use this
var data = '<?php echo $array;?>';
Your variable is in a different scope since you're not using the PHP include
function. Here's the easiest way I know to achieve what you want:
main.js
Since you cannot use PHP in a .js
file, declare your JavaScript variable before you call your script, like this:
<script type="text/javascript">
var array = '<?php echo $array ?>';
</script>
<script src="js/main.js"></script>
Then, in your main.js
file, just replace the code you posted by this:
$(document).ready(function() {
var data = array;
alert(data);
});