How do I include a PHP variable in an external javascript file?

Discussion in 'PHP' started by Imozeb, Apr 5, 2010.

  1. #1
    I want to include a PHP variable in an external javascript file. The PHP variable is used to set the javscript variable so the PHP variable is not being used. How would I do this?

    I've been trying this.


    Javascript code:
    
    javascriptvar = <?PHP echo($PHPvar); ?>;
    
    alert(javascriptvar);
    
    
    Code (markup):
    This code used to work, but now because it is in an external .js file it doesn't seem to work. Is this because the file type has to be .php. I thought that because I am including the .js file in the .php file it should just parse normally?

    Thanks.

    ~imozeb :)
     
    Imozeb, Apr 5, 2010 IP
  2. guardian999

    guardian999 Well-Known Member

    Messages:
    376
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    103
    #2
    myjavascript.php
    
    <?php
    header("Content-Type: text/javascript");
    echo "var javascriptvar = ' ".$phpvar." '; ";
    echo "alert(javascriptvar);";
    ?>
    
    PHP:
    ;)
     
    guardian999, Apr 5, 2010 IP
  3. Imozeb

    Imozeb Peon

    Messages:
    666
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Do I have to echo out all of my javascript code or is there an easier way?
     
    Imozeb, Apr 5, 2010 IP
  4. angelomaniac

    angelomaniac Peon

    Messages:
    24
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Then use this:

    
    <?php header("Content-Type: text/javascript"); ?>
    var javascriptvar = '<?php echo $phpvar; ?>';
    alert(javascriptvar);
    
    PHP:
     
    angelomaniac, Apr 5, 2010 IP