I'm trying to get a bit of PHP to execute inside of a .js file, but obviously don't know how to do it properly.
Basically the code is adding some HTML tags to my page, which I am using for a slideout contact form. However the contact form itself is done in Wordpress by a shortcode. So I'm trying to get the shortcode to work inside the code that makes the form slide out.
var phpTest = '<?php do_shortcode("[contact-form-7 id=\'1088\' title=\'Live Chat Form\']"); ?>';
// add feedback box
$this.html('<div id="fpi_feedback"><div id="fpi_title" class="rotate"><h2>'
+ thisSettings.title
+ '</h2></div><div id="fpi_content">'
+ phpTest
+ '</div></div>');
If I change the variable "phpTest" to a regular string with text, it shows up fine, I'm just not sure how to execute the php in this instance.
You can do a ajax post request to a .php file. It is a little dirty trick but it works
With that trick, you can basicaly do anything you want
I commented saying your question is not possible, however it is indeed possible. This is not recommended, but if you're not worried about the possible security holes, here is a way to accomplish your question:
Create a
.htaccess
file in the same directory as your.js
files, with the following:This will execute your JavaScript files as PHP, then fix the Content-Type for .js files automatically (because they're seen as text when you add the php handler).
Note: While this is a quick and dirty solution, a better way would be to use Ajax (see chiliNUT's Answer)
Suppose your filename is myscript.js:
in your head tag ( it must be an executable php file):
... ... in this way you are able to execute that file as if it were a php file
I think you can do something like this using AJAX:
JS code:
The do_shortcode_file.php must have something like this:
PHP code:
EDIT: The script type should always be
text/javascript
asapplication/javascript
may break compatibility with older browsers (I think IE8 and earlier will ignore the script tag with that type). The Content-type, however, should still beapplication/javascript
.You can't mix in php into a
.js
file, the way you would with a normal.php
file, since the.js
file is not preprocessed by the.php
engine the way your.php
files are.The most typical way to do this--including php in a js file--is to just have inline JS (stuff between
<script>
tags) in your .php file. Then it will work as expected.Another way to go is to make a js file within php, so start your .php file with
and then include it on your page like this