PHP in External JS file (driving me crazy!)

Hi,
I read several examples, tried them all out - and nothing works! Driving me crazy - completely insane! Maybe you guys can help :slight_smile:

My problem is simple:

file B.html includes this line:

<script type="text/javascript" src="B.js" defer="defer"></script>

file B.js is a regular JS file, yet I need to insert a PHP function in it (yeah - I know it will operate server-side before the page reaches the browser). I did something like:


(some js code)
[B]var user_id = <?php $a=100; $b=200; $c=$a+$b; echo($c);?>;
[/B]alert("Your user ID is:" + user_id);
(some more js code)

(What I expect is the browser to see the line as: var user_id = 300; )

Doesnโ€™t work. Renaming B.js to B.php did nothing.
What am I doing wrong?

Thanks!

You put php code in an external javascript file.

If your external JS has PHP, then the file needs to be a PHP file, then call it in the script src:

B.php


var user_id = <?php $a=100; $b=200; $c=$a+$b; echo($c);?>;
alert("Your user ID is:" + user_id);

Call it in your HTML file:


<script type="text/javascript" src="B.php"></script>