Include PHP inside JavaScript (.js) files

Viewed 248878

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?
11 Answers

Instead of messing with generic php-handlers do a 1-file exception using a rewrite:

Rename the .js-file to .php and rewrite the request to make it responde to a .js request. If the file is served by apache; add in .htaccess:

RewriteEngine on
RewriteRule myjsfile\.js myjsfile.php [L]

Secondly make the .php-file pretend to be a js-file. Inside the php-file start the file with:

<?php header('Content-Type: application/javascript'); ?>

Et voilĂ , you can now use php-tags in your ".js"-file.

Related