Php constants in javascript file

Possible duplicate:
Pass the PHP string to the Javascript variable (and delete the translation strings)

I am working on a project and it has already been done, but it needs one more tool and its use of language constants in javascript files.

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

alert("YOU Have VOTED BEFORE"); 

easily, the script will warn that the text

but what if we need to warn its language constant:

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

this will only work if echo the script as the inline code of my php ...

but how can we read and include php constants or $ vars for an external JavaScript file ???

+5
source share
5 answers

There is a way to do this using the 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 first weigh your options.

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

not to write too much code, refer to the link to find out how to get the value

+4
source

For a cleaner structure, I believe that the best way is to set all the data you get from PHP in one place, i.e. in the HTML that you use through PHP:

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

In the JavaScript file that you include later, you can access the value through MyNameSpace.config.something .

It also facilitates the reuse of the message.

+7
source

Actually, what you had was close to the right one.

  <?php // Valid constant names define("VOTED_BEFORE", "false"); ?> <script type="text/javascript"> alert("<?php echo VOTED_BEFORE;?>"); </script> 
+2
source

If it is not a PHP file, you cannot include PHP echo functions in it. I suggest that if you want to use a PHP variable in external js files, declare it as global in your PHP file before referencing external js.

 <script type="text/javascript"> var globalvar = '<?php echo _VOTED_BEFORE ?>' ; </script> <script type="text/javascript" src="externalfile.js"></script> 

Although not always a good idea to clutter up the global namespace.

+1
source

You can use cookies to store these constants and read them via JavaScript or you will have to use AJAX

-1
source

Source: https://habr.com/ru/post/910672/


All Articles