0

I would love to post some starting code in this question, but to be honest, I' stumped.

I'm looking for a way to use PHP within my .JS file.

I would like to be able to use real PHP functions inside my "stuff.js" and then be able to include it using:

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

Any thoughts? Thanks.

  • 4
    possible duplicate of [Parse a JavaScript file through PHP](http://stackoverflow.com/questions/3943198/parse-a-javascript-file-through-php) – Pekka Mar 02 '11 at 16:50
  • Please be aware of proper escaping when you output JS using PHP. – tobyS Mar 02 '11 at 16:54
  • Think of PHP as a program that is run ONLY on the server and the client sees the output after it has run. Javascript is sent to the client and then executed on the client computer, often based upon user interaction. You should quickly realize why it is not possible to have PHP executed in javascript on the client. – horatio Mar 02 '11 at 17:12

3 Answers3

1

You just have to write your JavaScript into a php file and then include it

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

I would recommend you keeping your JS functions in a .js file and the variable data that needs to be output dynamically could be output directly in the main php/html file:

<script type="text/javascript" language="JavaScript">
  var a = "<?php echo addslashes($a); ?>";
  // ...
</script>

Other possibility would be to tell your server to proccess *.js file with php but I wouldn't recommend that as it could cause some unexpected problems.

Czechnology
  • 14,832
  • 10
  • 62
  • 88
  • What if I wanted to echo or print something into the main file that's including the "whatever.php". Could I use JS to do that or..? –  Mar 02 '11 at 16:52
  • @Alexwhin, I'm not sure if I understand correctly your question but see my edit. I think it's a good practice to keep the pure javascript separated from the Javascript mixed with php. But that depends on your application. – Czechnology Mar 02 '11 at 16:58
1
<script src="/YOUR_PHP_FILE_PATH/file.php"></script>

Also add header in php file

header(Content-Type: text/javascript);
Manish Trivedi
  • 3,481
  • 5
  • 23
  • 29
0

It's impossible but you can use PHP file as a JavaScript file talking in a short way. ;)

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

And in whatever.php:

<?php
echo "var text = 'test';";
?>

alert(text);
hsz
  • 148,279
  • 62
  • 259
  • 315