66

I can access a PHP var with Javascript like this:

<?php
    $fruit = "apple";
    $color = "red";
?>

<script type="text/javascript">
    alert("fruit: " + "<?php echo $fruit; ?>"); // or shortcut "<?= $fruit ?>"
</script>

But what if I want to use an external JS file:

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

externaljs.js:

alert("color: " + "<?php echo $color; ?>");
FFish
  • 10,964
  • 34
  • 95
  • 136

12 Answers12

121

You don't really access it, you insert it into the javascript code when you serve the page.

However if your other javascript isn't from an external source you can do something like:

<?php
    $color = "Red";
?>
<script type="text/javascript">var color = "<?= $color ?>";</script>
<script type="text/javascript" src="file.js"></script>

and then in the file.js use color like so:

alert("color: " + color);
tirenweb
  • 30,963
  • 73
  • 183
  • 303
Don
  • 9,511
  • 4
  • 26
  • 25
  • 2
    That is exactly what I just came up with as well,. and what I was after. +1 for Don – FFish May 28 '10 at 12:53
  • 1
    Should be var color = "= $color ?>"; – Mark L May 28 '10 at 13:17
  • Sorry about that and thanks Mark L, I've corrected it in the post. – Don May 28 '10 at 13:34
  • 2
    I'd be happy with this solution if it wasn't for the fact that it's creating a global variable among the lower script tags. – Kacy Jan 04 '15 at 17:00
  • A great concept, but please do not use global variables! Also @Adam Joseph Looze - it's always best practice to use the "var" keyword when declaring javascript variables. Without "var", the variable will automatically be global(attached to the window object). – taykay08 Jul 15 '15 at 03:22
  • I assumed it would have to be global to be used in the external js file – Adam Joseph Looze Jul 15 '15 at 21:01
  • Why is the very poor coding practice? @SterlingArcher – mesqueeb Apr 08 '16 at 06:36
  • @mesqueeb http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript read this -- echoing directly to a JS variable is insecure – Sterling Archer Apr 08 '16 at 14:07
  • That was it. I had to pass some localization info from a PHP page to a JS page. – JayJay123 Jul 11 '21 at 05:40
17

You can also access data from php script in Javascript (I'll use jQuery here) like this

Create input hidden field within you php file like this

<input type="hidden" id="myPhpValue" value="<?php echo $myPhpValue ?>" />

in your javascript file:

var myPhpValue = $("#myPhpValue").val();
//From here you can the whaterver you like with you js Value
if(myPhpValue != ''){
//Do something here
}

This will do the job as well :)

Atanas Kovachev
  • 421
  • 5
  • 12
  • This will not work if you use ajax. PHP requires page refresh, whereas ajax is the opposite. – Dexter May 09 '22 at 02:20
8

What I've seen done is let .js files run through the php interpreter. Which I can not recommend.

What I do recommend is fetching the values through AJAX and have the PHP file return the value to the JS file. Which is a much cleaner method.

Ólafur Waage
  • 68,817
  • 22
  • 142
  • 198
6

First of all you have to understand that no program can actually have access to the other program's variable.

When you realize that, the rest is simple.
You can either set up a js variable in the main file and then include your external js, or make this external js dynamic, generated by PHP as well

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • Thanks for clarifying. I used your first solution. than and inside externaljs.js I access with alert(_fruit); – FFish May 28 '10 at 12:49
  • FFish… nice code example. I'd add that there is no need to prefix the JavaScript variable with an underscore as it exists in a different realm from the PHP variable, so there is no clash – Carl Aug 04 '23 at 09:06
4

What you likely want, is called Asynchronous JavaScript and XML (AJAX): http://www.w3schools.com/ajax/default.aspa

Basically, imagine being able to send messages from the clients JavaScript to your PHP scripts on the server. In the example you gave (externaljs.js), you would have the script ask the server what $color is, via HTTP. You can also point the script tag at a PHP script that generates the JavaScript you want. It depends on what you need to do.

It helps to have some understanding of taint checking, data verification, and security ;)

TerryP
  • 1,072
  • 1
  • 8
  • 13
3

As the others are saying, javascript doesn't have access to php variables. However, it does have access to the DOM. So, you can use php to add attributes to some page element. And then you can access those attributes with javascript.

e.g. <div id='apple' class='red'> is completely available to javascript

dnagirl
  • 20,196
  • 13
  • 80
  • 123
  • Excuse my poor understanding of Javascript/jQuery, but wouldn't it be possible to use a data-type?
    and then retrieve it via the data selector $('[data-color]').val(); or something similar?
    – dj.cowan Aug 02 '16 at 15:43
  • @dj.cowan Yes, using a data-type would be the preferred method now. But you still won't have direct access to php variables. You'll only have access to the values they held when the html was generated. – dnagirl Aug 08 '16 at 17:04
2

Don solution is good, furthermore if you want to use a php array in an external javascipt this can help you:

PHP:

<?php
    $my_php_array = [];
?>     

HTML:

<script type="text/javascript"> var my_js_array = <?php echo json_encode($my_php_array);?> ; </script>
<script src = "../public/js/my-external-js.js"></script>

Javasript: (You can now use the array like a normal Javascript array)

 my_js_array[0] 
 my_js_array.length
Mr Rubix
  • 1,492
  • 14
  • 27
1

externaljs.js is a static file. Of course it can't access PHP data. The only way to pass PHP data to a js file would be to physically alter the file by writing to it in your PHP script, although this is a messy solution at best.

Edit in response to Ólafur Waage's answer: I guess writing to the js file isn't the only way. Passing the js through the PHP interpreter never crossed my mind (for good reason).

Manos Dilaverakis
  • 5,849
  • 4
  • 31
  • 57
1
<script type="text/javascript" src="externaljs.js"></script>

You could change it to

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

And the PHP script could just write JavaScript like that :

<?php
$fruit = "apple";
echo 'var fruit = '.json_encode($fruit);
...

Though using AJAX like said Sepehr Lajevardi would be much cleaner

Serty Oan
  • 1,737
  • 12
  • 19
1

2017-2018 and above solution:

Since nobody bringed it up yet and I guess no one thought of combining the functions base64_encode and json_encode yet, you could even send PHP Array variables like that:

index.php

<?php
      $string = "hello";
      $array = ['hi', 'how', 'are', 'you'];
      $array = base64_encode(json_encode($array));

Then you could just load your desired js file with the parameter for a query string like this:

echo '<script type="text/javascript" src="js/main.php?string='.$string.'&array='.$array.'">';

Then js/main.php will look like this for example. You can test your variables this way:

js/main.php

    <?php
    if ($_GET['string']) {
        $a = $_GET['string'];
    }
    if ($_GET['array']) {
        $b = $_GET['array'];
    }
    $b = json_decode(base64_decode($b));

    echo 'alert("String $a: + '.$a.'");';
    echo 'alert("First key of Array $array: + '.$b[0].'");';
    exit();
    ?>

The following will then output when you open your index.php. So you see, you don't open js/main.php and you still got the javascript functionality from it.

enter image description here

AlexioVay
  • 4,338
  • 2
  • 31
  • 49
1

You can include() them just as you would anything else:

<?php
    $fruit = "apple";
    $color = "red";
?>

<script type="text/javascript">
    <?php include('/path/to/your/externaljs.js'); ?>
</script>

This will basically render the external file as inline js. The main disadvantage here is that you lose the potential performance benefit of browser caching. On the other hand, it's much easier than re-declaring your php variables in javascript.

0

You cant do that and dont try to as this is not a recommended approach, However you can pass php variables as a function parameters to function written in external js

sushil bharwani
  • 29,685
  • 30
  • 94
  • 128