Include PHP inside JavaScript (.js) files
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>
Using PHP in .JS file?
Create an file with php extension and include it in your website as javascript.
map.api.js
<?php
header("Content-type: application/javascript");
//my php here
?>
//my javascript here
In your HTML File:
<script type="text/javascript" src="map.api.php"></script>
If you wan't to hide the php extension, you can work with mod_rewrite (Apache):
RewriteEngine on
RewriteRule ^map.api.js$ map.api.php
How to include in .php a .html with links to a .js that has php codes
In your PHP file, create a global variable containing your JSON in a tag:
<script>var myNum = <?php echo json_encode($value); ?>;</script>
and then reference that variable in your script file with myNum
.
How do I embed PHP code in JavaScript?
If your whole JavaScript code gets processed by PHP, then you can do it just like that.
If you have individual .js
files, and you don't want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript.
For example, in your index.php
(or wherever you specify your layout), you'd do something like this:
<script type="text/javascript">
var my_var = <?php echo json_encode($my_var); ?>;
</script>
You could then use my_var
in your JavaScript files.
This method also lets you pass other than just simple integer values, as json_encode()
also deals with arrays, strings, etc. correctly, serialising them into a format that JavaScript can use.
Related Topics
Compile a Referenced Less File into CSS with PHP Automatically
How to Force PHP to Use Strings for Array Keys
How to Solve a Timeout Error in Laravel 5
Undefined Class Constant 'Mysql_Attr_Init_Command' with Pdo
Pdo Drivers No Value in Windows
How to Delete Files from Directory Based on Creation Date in PHP
How to Decrypt a Password Hash in PHP
Why I Can Not Login to Magento Backend Using Google Chrome
Which Line Break in PHP Mail Header, \R\N or \N
How to Use PHP Array with SQL in Operator
Multiple Index Variables in PHP Foreach Loop
Finding Common Prefix of Array of Strings
Using PHP to Execute Multiple MySQL Queries
Symfony2: After Successful Login Event, Perform Set of Actions
Fatal Error: Call to Undefined Function Socket_Create()