8

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.

KVDD
  • 652
  • 2
  • 9
  • 21
  • 4
    PHP is executed before javascript is called, so this would **"never"** work. – Nahydrin May 09 '14 at 21:35
  • 1
    Try saving the file as .php instead of .js. Then put this code inside ` – imtheman May 09 '14 at 21:35
  • 2
    PHP is executed on the server. Javascript is executed on the client's machine. Your client's computer can't execute your PHP program because it has no knowledge of the PHP program (it never sees it, only the server sees it). If you want to perform some PHP functionality and report it back to the user, without reloading the page, look into AJAX. Jquery has a pretty simple implementation of it (http://api.jquery.com/jquery.ajax/) – Cully May 09 '14 at 21:37
  • @imtheman PHP doesn't work that way. – Cully May 09 '14 at 21:37
  • You might just try this solution: [How to embed php in javascript?](http://stackoverflow.com/questions/3352576/how-to-embed-php-in-javascript) – jray May 09 '14 at 21:40
  • 1
    @CullyLarson why wouldn't it work? The php code isn't using any javascript variables. It is just literally echo'ing out the result from a php function which is most likely static. – Jonathan Kuhn May 09 '14 at 21:40
  • @JonathanKuhn If it's really static, it probably should be statically generated. Or you can configure your server to parse JS files with PHP and cache them from then on. – Ruan Mendes May 09 '14 at 21:46
  • @JuanMendes static as in it might look up a value in the database. The value as far as php is concerned is dynamic, might change. But as for js, the result is just a string. – Jonathan Kuhn May 09 '14 at 21:53

5 Answers5

17

EDIT: The script type should always be text/javascript as application/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 be application/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

<?php
header("Content-type: application/javascript");
?>
var jsvar='something';
var othervar='<?php echo $phpVar; ?>';
//<?php //some php ;?>

and then include it on your page like this

<script src='myjs.php' type='text/javascript'></script>
chiliNUT
  • 18,989
  • 14
  • 66
  • 106
  • 5
    I upvoted the answer. However, you actually configure your webserver so that JS files that are processed by PHP. That is a very bad idea though, tightly couples your JS to your server code. Better use AJAX or at the very least create a single JSON object in PHP that will be used by the JS – Ruan Mendes May 09 '14 at 21:43
  • @JuanMendes yes that is certainly an option, but as you said, it is a terrible idea, so I did not include it. I was explaining what are IMO 2 good ways to do it, not EVERY way to do it. – chiliNUT May 09 '14 at 21:44
  • I agree with @JuanMendes: better to use AJAX – jray May 09 '14 at 21:46
  • I think generating JS in PHP is a bad idea altogether. At the very least, generate just a single JSON object that becomes the only coupling between your JS and the PHP (and you won't have encoding problems with quotes and newlines. If you use AJAX, then it's even more well separated, but I understand that some must support JS disabled browsers. – Ruan Mendes May 09 '14 at 21:47
  • 2
    There are any number of situations where you don't want to make a secondary ajax request on top of the page load. packing everything in a single json object I think is probably the best way to go. – chiliNUT May 09 '14 at 21:51
  • 1
    @chiliNUT Yes, that is very true, besides supporting JS disabled browsers, we sometimes don't want an extra request. However, doing the extra processing in PHP may delay the page from being displayed if it's intensive work. Therefore, the person deciding has to weigh both factors. – Ruan Mendes May 09 '14 at 21:53
  • 1
    Thanks @chiliNUT. I will try and re-work the code into a .php file, and see if I can't get it working :) – KVDD May 09 '14 at 22:14
5

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:

AddHandler application/x-httpd-php .js

<FilesMatch "\.js$">
    Header set Content-Type "text/javascript; charset=utf-8"
</FilesMatch>

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)

Community
  • 1
  • 1
Nahydrin
  • 13,197
  • 12
  • 59
  • 101
  • Can you suggest a better way since you know the downsides of this? By the way, I don't think the main problem is a security hole. – Ruan Mendes May 09 '14 at 21:49
  • The form I'm trying to get to show has it's own security/validation, however I assume you mean it would open up different security issues. Rather than using a blanket ".js" could I use the exact .js file name, so it only affects the one .js file and not all of the .js on my website? – KVDD May 09 '14 at 22:08
  • @KerynGill Yes you can, replace `\.js$` with `^filename.js$`. – Nahydrin May 09 '14 at 22:13
  • @JuanMendes I added a link to chiliNUT's answer – Nahydrin May 09 '14 at 22:16
1

You can do a ajax post request to a .php file. It is a little dirty trick but it works

$.post('thePhpFile',{var1:var1,var2:var2},function(result){
    //Code to do with the resulted... like $("#div").html(result);
});

With that trick, you can basicaly do anything you want

Jayo2k
  • 251
  • 3
  • 14
0

I think you can do something like this using AJAX:

JS code:

var xmlhttp;
if (window.XMLHttpRequest){
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}else{
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        $this.html('<div id="fpi_feedback"><div id="fpi_title" class="rotate"><h2>'
        + thisSettings.title
        + '</h2></div><div id="fpi_content">'
        + xmlhttp.responseText
        + '</div></div>');
    }
}

xmlhttp.open("GET","do_shortcode_file.php",true);
xmlhttp.send();

The do_shortcode_file.php must have something like this:

PHP code:

<?php
echo do_shortcode("[contact-form-7 id=\'1088\' title=\'Live Chat Form\']");
0

Suppose your filename is myscript.js:

in your head tag ( it must be an executable php file):

<head>
<script type="text/javascript">
<?php 
require_once 'myscript.js';
?>
</script>

... ... in this way you are able to execute that file as if it were a php file

Hidran
  • 328
  • 1
  • 6