[ACCEPTED]-php constants in a javascript file-javascript
For a cleaner structure, I think the best 6 way is to set all the data you get from 5 PHP in one place, i.e. in the HTML you serve 4 via PHP:
<script>
var MyNameSpace = {
config:
something: "<?php echo _VOTED_BEFORE ?>"
}
}
</script>
In the JavaScript file you include 3 afterwards, you can access the value via 2 MyNameSpace.config.something
.
This makes it also easier to reuse the 1 message.
There is a way of doing this using a query 5 string in the script path
See my answer here
How to pass variable from php template to javascript
Unfortunately 4 this will break the cache for your js file 3 so weight your options first
<script type="text/javascript" src="script.js?flag=<?php echo _VOTED_BEFORE?>"></script>
for the sake 2 of not writing too much code refer to the 1 link to see how to retrieve the value
If it's not a PHP file, you cannot include 6 PHP echo functions in it. I suggest that 5 if you want to use a PHP variable in your 4 external js files then declare it as a global 3 in your PHP file before you reference the 2 external js.
<script type="text/javascript">
var globalvar = '<?php echo _VOTED_BEFORE ?>' ;
</script>
<script type="text/javascript" src="externalfile.js"></script>
Though it's not always a good 1 idea to clutter the global namespace.
Actually, what you had was close to being 1 proper.
<?php
// Valid constant names
define("VOTED_BEFORE", "false");
?>
<script type="text/javascript">
alert("<?php echo VOTED_BEFORE;?>");
</script>
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.