Use PHP variable in JS file

5

I want to put PHP code in a JavaScript file, it is not an HTML file. Like for example here:

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

With the PHP code would it be something like this?

document.getElementById('lbljour').innerHTML = <?php echo trad($f_lng,"Jour "); ?> + date_today;
    
asked by anonymous 24.10.2014 / 11:29

3 answers

4

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

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

And I use it in JS:

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

In fact, lang in PHP will be created according to the current language, or it may contain all language variants in the object.

    
24.10.2014 / 11:52
2

You can not put PHP code in a .js file because PHP does not interpret files with this termination.

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>
    
24.10.2014 / 11:40
1

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

Within the file php you can enter the following:

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