SitePoint Sponsor

User Tag List

Results 1 to 3 of 3

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    Jun 2009
    Posts
    5
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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

    My problem is simple:

    file B.html includes this line:
    Code:
    <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:
    Code:
    (some js code)
    var user_id = <?php $a=100; $b=200; $c=$a+$b; echo($c);?>;
    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!

  2. #2
    Non-Member
    Join Date
    Apr 2011
    Location
    no fixed address
    Posts
    851
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by SalmonTrout View Post
    What am I doing wrong?
    You put php code in an external javascript file.

  3. #3
    SitePoint Addict
    Join Date
    Dec 2005
    Posts
    336
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    If your external JS has PHP, then the file needs to be a PHP file, then call it in the script src:

    B.php
    Code:
    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:
    Code:
    <script type="text/javascript" src="B.php"></script>


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •