Re: Including JS code that uses PHP
| From: | Larry Martell | Date: | Tue, 05 Sep 2017 22:35:31 +0000 |
| Subject: | Re: Including JS code that uses PHP | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-326208@lists.php.net to get a copy of this message | ||
On Tue, Sep 5, 2017 at 5:35 PM, Christoph M. Becker <cmbecker69@gmx.de> wrote:
> On 05.09.2017 at 22:58, Larry Martell wrote:
>
>> I have some javascript code that has PHP in it like this:
>>
>> var CLIENT_ID='<?php echo $CLIENT_ID; ?>'
>>
>> If I put the JS code directly in a php file with:
>>
>> <script type="text/javascript">
>> .
>> .
>> .
>> </script>
>>
>> Then at run time CLIENT_ID has the value I want. I want to use the
>> same JS code in many php files. But if I include the JS code like
>> this:
>>
>> <script src="login.js" type="text/javascript">
>>
>> Then that php code does not get run and CLIENT_ID has the literal
>> string '<?php echo $CLIENT_ID; ?>'
>>
>> Is there a way I can reuse my JS file and still have embedded PHP in it?
>
> There might be, but consider to simply pass the required values as data
> to JavaScript instead. A very simplistic way might be:
>
> PHP file:
>
> <?php $serverData = ['client_id' => CLIENT_ID']?>
> <script>var serverData = <?=json_encode($serverData)?></script>
> <script src="login.js">
>
> JavaScript file (login.js):
>
> alert(serverData.CLIENT_ID);
Thanks - I did a variation of that and it worked.