Use PHP variable in JS file

Asked

Viewed 415 times

5

I want to put PHP code in Javascript file, not HTML file. As for example here:

    document.getElementById('lbljour').innerHTML = "Jour " + date_today;

With PHP code would look something like this?

document.getElementById('lbljour').innerHTML = <?php echo trad($f_lng,"Jour "); ?> + date_today;
  • Exactly, this way works. It didn’t work?

  • 2

    if the file extension is . js, it is not. but inside a. php file with javascript inside it

  • Does not work. Yes is a. js file

  • 1

    You can create a global variable with the PHP content in the file that calls the .js. In the .js you use the global variable.

  • You have already answered the question below with what I told you.. The . js file has a lot of code or just that line?

  • Sorry for the comment... but what you’re doing at the very least results in a major security breach and an unorthodox way to achieve what you want. Javascript is a language that runs on the client and php is a language for the server...if this type of use is possible in javascript... then many services would be easily broken. The opposite is possible...ie by Php.

Show 1 more comment

3 answers

4


I use the following technique, in the PHP file create a global object:

<?php ?>
<script>
var lang = {
        day: 'Jour'
    };
</script>
<?php ?>

And use in JS:

document.getElementById('lbljour').innerHTML = lang.day + date_today;

And in fact, the lang in PHP will be created according to the current language, or can contain all language variants in the object.

  • I also use them this way, I use them both depending on what suits me most.

  • Exact, depends on the volume of JS/PHP you have create.

  • I am following your example, and want to pass this php variable to js. I used this in my php file "<? php ? ><script>var lang = $lng;</script><? php ? >" and in the js file, I want to show "Alert(lang);"

  • I think you have to make one echo in that case: var lang = "<?php echo $lng; ?>";, attention to quotes in JS if you want to define a string.

2

Cannot place PHP code in a file .js because PHP does not interpret files with that ending.

You can create a script in the PHP file:

<script type="text/javascript">
    document.getElementById('lbljour').innerHTML = <?php echo trad($f_lng,"Jour "); ?> + date_today;
</script>

1

If you are trying to write PHP code inside a file .JS is not possible. Since the server will not read the PHP inside. If you only have that code in that file, I advise you to put the code inside the file .php.

Inside the file php you can put the following:

<script type="text/javascript">
    document.getElementById('lbljour').innerHTML = <?php echo trad($f_lng,"Jour "); ?> + date_today;
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.