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.
.php
file containing the PHP function in the .js
file?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?Technically it's not the only way, but it's certainly a safe way. That said, one shouldn't be building JavaScript with PHP to begin with. It depends on what kind of data would you like to send.
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file.
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"
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With