Include PHP inside JavaScript (.js) files

241,033

Solution 1

7 years later update: This is terrible advice. Please don't do this.

If you just need to pass variables from PHP to the javascript, you can have a tag in the php/html file using the javascript to begin with.

<script type="text/javascript">
    var phpVars = <?php echo json_encode($vars) ?>;
</script>
<script type="text/javascript" src="yourScriptThatUsesPHPVars.js"></script>

If you're trying to call functions, then you can do this like this

<script type="text/javascript" src="YourFunctions.js"></script>
<script type="text/javascript">
    // assume each element of $arrayWithVars has already been json_encoded
    functionOne(<?php echo implode(', ', $arrayWithVars); ?>);
    functionTwo(<?php echo json_encode($moreVars) ?>, <?php echo json_encode($evenMoreVars) ?>);
</script>

Solution 2

AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js
<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>

Add the above code in .htaccess file and run php inside js files

DANGER: This will allow the client to potentially see the contents of your PHP files. Do not use this approach if your PHP contains any sensitive information (which it typically does).

If you MUST use PHP to generate your JavaScript files, then please use pure PHP to generate the entire JS file. You can do this by using a normal .PHP file in exactly the same way you would normally output html, the difference is setting the correct header using PHP's header function, so that the correct mime type is returned to the browser. The mime type for JS is typically "application/javascript"

Solution 3

PHP and JS are not compatible; you may not simply include a PHP function in JS. What you probably want to do is to issue an AJAX Request from JavaScript and send a JSON response using PHP.

Solution 4

A slightly modified version based on Blorgbeard one, for easily referenceable associative php arrays to javascript object literals:

PHP File (*.php)

First define an array with the values to be used into javascript files:

<?php
$phpToJsVars = [
  'value1' => 'foo1',
  'value2' => 'foo2'    
];
?>

Now write the php array values into a javascript object literal:

<script type="text/javascript">
var phpVars = { 
<?php 
  foreach ($phpToJsVars as $key => $value) {
    echo '  ' . $key . ': ' . '"' . $value . '",' . "\n";  
  }
?>
};
</script>

Javascript file (*.js)

Now we can access the javscript object literal from any other .js file with the notation:

phpVars["value1"]
phpVars["value2"]

Solution 5

This is somewhat tricky since PHP gets evaluated server-side and javascript gets evaluated client side.

I would call your PHP file using an AJAX call from inside javascript and then use JS to insert the returned HTML somewhere on your page.

Share:
241,033

Related videos on Youtube

GregH
Author by

GregH

Updated on May 27, 2021

Comments

  • GregH
    GregH almost 2 years

    I have a JavaScript file (extension .js, not .html) containing several JavaScript functions.

    I want to call one of the PHP functions in a PHP file containing only several PHP functions from within one of the JavaScript functions.

    • Is that possible?
    • Would I need to "include" the .php file containing the PHP function in the .js file?
    • How would I do that?
      For example, say I had a file called myLib.php containing a function called myFunc that takes two parameters (param1 and param2). Then I have a .js file containing a function called myJsFunc. How would a call the myFunc (PHP) from within the myJsFunc (JavaScript function)? Wouldn't I need to include the PHP file somehow in the .js file?
    • meder omuraliev
      meder omuraliev almost 13 years
      This is way too vague. Please tell us what those functions do.
    • Amit Patil
      Amit Patil almost 13 years
      JavaScript executes on the user's browser. PHP executes on the server. Their functions cannot call each other. You need to understand the lifecycle of how PHP creates a web page including any JavaScript source code inside that page, and then JS starts running in the browser long after PHP has finished. Then if you really need to have the client and server talk to each other, look at XMLHttpRequest (AJAX et al).
    • Gordon
      Gordon almost 13 years
    • GregH
      GregH almost 13 years
      I am basically doing AJAX. Effectively, I am constructing a url in a JS function that calls the PHP via a XMLHttpRequest.
  • quantumSoup
    quantumSoup almost 13 years
    +1 You don't even need a JSON response, it can really be anything; as long as you can parse/use it with JS in a meaningful way.
  • GregH
    GregH almost 13 years
    Right...this is what I am doing. I am constructing the a URL calling a php function inside the javascript function that uses XMLHttpRequest. The question is can I call a php function inside of an included .php file or do I have to isolate the PHP code in a single file that contains the straight PHP code (no function) that the js code calls directly. I just don't want to have a bunch of PHP files with code in them sitting around. I'd like to incorporate the code in PHP functions in a .php file.
  • Josiah
    Josiah almost 13 years
    You could have all your functions in a single file then create a .php file that only has the include line to your functions file and a call to that function.
  • quantumSoup
    quantumSoup almost 13 years
    @GregH What you want is to have an API that your JS function can call (via AJAX or what not), specifying functions and arguments. This API could be in a single file or multiple, it depends on what you want.
  • John
    John almost 13 years
    Once you use AJAX to call the .php script on your server you can do anything in your .php script that you would normally do. There is no difference. It sounds like that is what is mixing you up. You can include any other script in the execution that you need to.
  • John
    John almost 13 years
    Also you can include arguments via post or get to specify what files you need to include in the .php function to only pull what you need.
  • quantumSoup
    quantumSoup almost 13 years
    Of course what @John said about specifying includes needs to be properly sanitized.
  • JVE999
    JVE999 about 9 years
    Now the php pages get downloaded on access
  • sgrif
    sgrif over 7 years
    It's been nearly 6 years, and this still gets upvoted occasionally. This is absolutely terrible advice. You should strongly consider why you're needing to do this, and consider an alternative structure. If these variables can change over time, perhaps make an AJAX endpoint which represents what you need. If they really only matter at the time of the request, at least make a <meta> tag for each of the variables and read that, rather than generating JavaScript with PHP spitting into it.
  • Marc B
    Marc B almost 7 years
    it's utterly pointless and injection prone as well. phpvars = <?php echo json_encode($vars); ?>; is guaranteed to produce syntactically correct JS, whereas the above will kill the entire script block if there's a single ' or other JS meta-char anywhere in the inserted text.
  • Ulad Kasach
    Ulad Kasach almost 7 years
    Why is this better than json_encode($phpToJsVars)?
  • Pharaoh Tools
    Pharaoh Tools over 6 years
    Using Uniter along with php.js would allow the OP to run his php files directly from within his JS environment
  • mvndaai
    mvndaai over 6 years
    Can you explain how this "will allow the client to potentially see the contents of your PHP file"
  • Julix
    Julix almost 6 years
    upvoted, just to bug you :P - since it is a highly upvoted answer maybe make the alternative (better solution) part of the answer instead of just a comment?
  • miken32
    miken32 almost 2 years
    Sure it's not great architecturally, but for beginners needing a quick and dirty method it works fine. I've added json_encode() to the answer to make it a little safer.