Executing PHP Code Inside a .Js File

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



Leave a reply



Submit