Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php constants in a javascript file [duplicate]

Tags:

javascript

php

Possible Duplicate:
Pass a PHP string to a Javascript variable (and escape newlines)

I'm working on a project and it's already done, but it needs one more midification and its applying language constants in javascript files.

consider we include a javascript file and in that we have something like this

            alert("YOU Have VOTED BEFORE");

easy like that , the script will alert that text

but what if we need to alert a language constant of it :

            alert("<?php echo _VOTED_BEFORE?>");

this will be worked only if echo the script like inline of my php codes ...

but, how can we read and include php constants or $vars for a outside JavaScript file ???

like image 931
Mac Taylor Avatar asked Jun 19 '11 08:06

Mac Taylor


4 Answers

For a cleaner structure, I think the best way is to set all the data you get from PHP in one place, i.e. in the HTML you serve via PHP:

<script>
    var MyNameSpace = {
        config:
            something: "<?php echo _VOTED_BEFORE ?>"
        }
    }
</script>

In the JavaScript file you include afterwards, you can access the value via MyNameSpace.config.something.

This makes it also easier to reuse the message.

like image 104
Felix Kling Avatar answered Nov 09 '22 22:11

Felix Kling


There is a way of doing this using a query string in the script path

See my answer here

How to pass variable from php template to javascript

Unfortunately this will break the cache for your js file so weight your options first

<script type="text/javascript" src="script.js?flag=<?php echo _VOTED_BEFORE?>"></script>

for the sake of not writing too much code refer to the link to see how to retrieve the value

like image 26
Ibu Avatar answered Nov 10 '22 00:11

Ibu


Actually, what you had was close to being proper.

 <?php
 // Valid constant names
 define("VOTED_BEFORE", "false");
 ?>

<script type="text/javascript">
    alert("<?php echo VOTED_BEFORE;?>");
</script>     
like image 2
stefgosselin Avatar answered Nov 09 '22 22:11

stefgosselin


If it's not a PHP file, you cannot include PHP echo functions in it. I suggest that if you want to use a PHP variable in your external js files then declare it as a global in your PHP file before you reference the 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 idea to clutter the global namespace.

like image 2
Jivings Avatar answered Nov 10 '22 00:11

Jivings