Reputation: 1071
I am facing a little js/php issue. I have 2 different files (a .php one and a .js one containing some scripts the .php page will execute). I would like to send a php variable to the .js page. I looked over the internet but did not find anything that could help me... Thanks for your help !
Upvotes: 0
Views: 66
Reputation: 3557
You can't send php variable directly to js file. For this purpose you have to write php value in a hidden or text field then get that value in js.
Upvotes: 0
Reputation: 549
You can try to embed the php variable in an hidden input field and try to access that input field in javascript.
<input type = "hidden" id = "phpvar" value <?php echo $hiddenVar; ?> />
in javascript
var hiddenPhpVar = document.getElementById('phpvar').value;
Upvotes: -1
Reputation: 18861
One solution is to define a JS variable in the HTML (produced by your PHP script):
<script type="text/javascript">
var SOME_VAR = <?= json_encode($myvariable) ?>;
</script>
I'm using json_encode()
, since it will add quotes around strings, and write arrays etc so that it's valid JavaScript.
After that, link the external JS file, in which you can use SOME_VAR
with the value that came from PHP.
Upvotes: 2