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.

8
  • 4
    PHP is executed before javascript is called, so this would "never" work. Commented May 9, 2014 at 21:35
  • 1
    Try saving the file as .php instead of .js. Then put this code inside <script> tags. I know this works with asp, I think it works with php too. Commented May 9, 2014 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 (api.jquery.com/jquery.ajax) Commented May 9, 2014 at 21:37
  • @imtheman PHP doesn't work that way. Commented May 9, 2014 at 21:37
  • 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. Commented May 9, 2014 at 21:40

5 Answers 5

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>
Sign up to request clarification or add additional context in comments.

7 Comments

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
@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.
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 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.
Thanks @chiliNUT. I will try and re-work the code into a .php file, and see if I can't get it working :)
|
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)

4 Comments

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.
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?
@KerynGill Yes you can, replace \.js$ with ^filename.js$.
@JuanMendes I added a link to chiliNUT's answer
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

Comments

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

Comments

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\']");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.