PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » HTAccess » Use PHP inside JavaScript

Use PHP inside JavaScript

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.

Subscribe to The Thread

  1. drivel says:

    Could you use this for stylesheets?

  2. Yasin says:

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

  3. sam says:

    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; ?>);

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~