[ACCEPTED]-php constants in a javascript file-javascript

Accepted answer
Score: 12

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:

    var MyNameSpace = {
            something: "<?php echo _VOTED_BEFORE ?>"

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.

Score: 4

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

Score: 2

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 type="text/javascript" src="externalfile.js"></script>

Though it's not always a good 1 idea to clutter the global namespace.

Score: 2

Actually, what you had was close to being 1 proper.

 // Valid constant names
 define("VOTED_BEFORE", "false");

<script type="text/javascript">
    alert("<?php echo VOTED_BEFORE;?>");

More Related questions