treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Use PHP inside JavaScript

Last updated on:

This has only really been tested on Media Temple (gs) servers.

In the folder with the JavaScript, the .htaccess file should include:

<FilesMatch "^.*?api.*?$">
SetHandler php5-script
</FilesMatch>

In that above example, any file that includes the string "api" will be processed as PHP. Feel free to alter that RegEx.

Then in the JavaScript file itself, set the ContentType back to JavaScript:

<?php
	// Sets the proper content type for javascript
	header("Content-type: application/javascript");
?>

That will ensure browsers reading the file will interpret it as JavaScript. Now you can use <php ... ?> tags in the JavaScript file to do whatever PHP stuff you need to do.

View Comments

Comments

  1. drivel
    Permalink to comment#

    Could you use this for stylesheets?

  2. Yasin
    Permalink to comment#

    Nice one can you give some explanatory example how all its work

  3. sam
    Permalink to comment#

    i dont think i can understand this without looking at a working example

  4. If I’ve understood it correctly, an example would be to have a file called:

    myjavascript.api.js

    Link to it in your HTML:

    <script src=’js/myjavascript.api.js’ type=’text/javascript’></script>

    Then, in the myjavascript.api.js itself, you can now use PHP code:

    <?php
    // Sets the proper content type for javascript
    header(“Content-type: application/javascript”);
    ?>

    // JS Code
    function myJavascriptFunction(variable) {
    // Do stuff with variable
    }

    myJavascriptFunction(<?php echo $variable_from_db; ?>);

  5. It quite valuable thing you shared as a trick and in some cases it will be really needed. However, before using it we have to clear what is more favorite for us: performance or this way to get PHP vars inside JS. Because when applying this trick, JS file is going to load much more slower, because it is loading as PHP file.

    Thanks anyway.

  6. Jon
    Permalink to comment#

    Does anyone know if this would work in a J2EE environment? I have a web application built in eclipse with JavaScript (jsp and jspf files) that I need to do some server stuff on the client side with Java and can’t get to the Java functions so I was going to try and use PHP to do it on the client side. Just some file manipulation…

    Thanks!
    Jon

  7. sentio
    Permalink to comment#

    can u post me all lastest updates in my mail,Thanx

  8. Permalink to comment#

    Awesome trick, :) I love it. Thanks

Leave a Comment

Use markdown or basic HTML and be nice.