Include PHP Inside JavaScript (.Js) Files

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

Any reason not to add js files using php include?

All the answers probably don't understand what are you asking.
You are not including javascript with php include, you are including part of your html code that contains links to your js files.

Your second solution (with inlcude inside index.php file and scripts.html) is absolutely ok. Especially if you have multiple templates where you include scripts.html.

If you use your first (historic) solution on multiple pages and you want to remove one js file, it will cost you more work to edit these files. It is also more prone to errors, you can easily forget to edit one of your templates.

Don't be afraid to use the new technique. Browser output will be the same as in the first, static file and all browsers will cache js files the same way.

Including PHP variables in an external JS file?

My solution combines several techniques, some of which are already mentioned within the answers to this question.

Yes, separate PHP from JS

First of all: yes, you should separate your JS from PHP. You can put it in a separate file, but you will need to make some changes into your current code. Do not make JS file dynamically generated - it actually kills the advantages of separating JS code into separate file (you cannot cache it etc.).

Common variables as global variables / function arguments

Next, store your common variables as global variables in the header of HTML file (you do not really have much choice, although there are other alternatives), preferably grouped in one object:

var Globals = <?php echo json_encode(array(
'active_user_id' => $active_user->id,
'token' => $token,
'hash' => $hash,
)); ?>;

Alternatively you can pass all of them as argument(s) to the function you will call, but I assumed you are using them also in other places in your script.

Container-dependent data stored in data- attributes

Then use data- attributes for storing real data associated with containers. You won't need post1/post2/post3-like classes and separate event handlers for them:

<div data-post-id="10">here is something</div>

instead of eg.:

<div class="post10">here is something</div>

How to read globals and data- attributes from external JS file

And then your JavaScript may look like:

$(document).ready(function(){
$('[data-post-id]').click(function() {
var el = $(this);
var data = {
'post_id': el.data('post-id'),
'user_id': Globals.active_user_id
};
data[Globals.token] = Globals.hash;
$.ajax({
'type': 'POST',
'url': 'http://domain.com/ajax/add_love',
'data': data,
'dataType': 'json',
'success': function(response) {
el.html(response.total_loves).toggleClass('loved');
}
});
return false;
});
});

And this should be sufficient (although I did not test it).

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.

include php in a js file

change the file extension of your javascript file to .php and use that file instead example

<script type="text/javascript" src="test.php"></script>

Also set the correct header on top of the file using

<?php
header("Content-type: text/javascript");
?>

php within js-file Wordpress

As Erik earlier posted, the file extension for the JavaScript-file is meaningless, as it in the end all comes down to the content. Upon encountering this situation during development, I found that I needed to add the following to the top of the so called JavaScript-file:

<?php

//Let's set the header straight
header('Content-type: text/javascript');

//Get the WP-specifics, so that we can use constants and what not
$home_dir = preg_replace('^wp-content/plugins/[a-z0-9\-/]+^', '', getcwd());
include($home_dir . 'wp-load.php');
?>

This ensures that you get the definitions into your JavaScript-file, and you can use the example above with themes too (just make sure you change the /plugins into /themes instead).



Related Topics



Leave a reply



Submit