Access PHP var from external javascript file

You can also access data from php script in Javascript (I'll use jQuery here) like this

Create input hidden field within you php file like this

<input type="hidden" id="myPhpValue" value="<?php echo $myPhpValue ?>" />

in your javascript file:

var myPhpValue = $("#myPhpValue").val();
//From here you can the whaterver you like with you js Value
if(myPhpValue != ''){
//Do something here
}

This will do the job as well :)


You don't really access it, you insert it into the javascript code when you serve the page.

However if your other javascript isn't from an external source you can do something like:

<?php
    $color = "Red";
?>
<script type="text/javascript">var color = "<?= $color ?>";</script>
<script type="text/javascript" src="file.js"></script>

and then in the file.js use color like so:

alert("color: " + color);

What I've seen done is let .js files run through the php interpreter. Which I can not recommend.

What I do recommend is fetching the values through AJAX and have the PHP file return the value to the JS file. Which is a much cleaner method.