Use PHP code in external Javascript file
Asked Answered
T

5

17

I am just wondering if it's possible to use external JS file that contains PHP code.

my external JS

$(document).ready(function(){

    $('#update').click(function(){
    var tableVal={};
    // a bit of php code I need in JS
    var search_city=<?php echo $_SESSION['search_city'];?>';
$.post('<?=base_url()?>/project_detail/pub', {'tableVal':tableVal},function(message)

        })
    })
})

my view page

<script type="text/javascript" src="<?= base_url();?>js/external.js"></script>

The JS doesn't work as I assume that the PHP code in JS is the problem. Any thoughts? Thanks a lot.

Touching answered 31/1, 2012 at 16:25 Comment(2)
The preprocessor will not parse the file unless the file ends in an extension that maps to the right content type, or you tell your web server that PHP should handle requests for files that end in .jsMcsweeney
In another words, change "external.js" to "external.php".Brokerage
O
22

You can do it by either renaming you js file to php and using this link in script tag src (as pointed in other answers)

While this may seems a good and easy way there is many reason not to do this.

  • Caching (your generated script will not be cached, this may be changed but require additional work)
  • Memory consumption (every request to this generated js file will require php)

You can simply changed to something like this to get it done (in a better way, IMO):

<script type="text/javascript">
  var Settings = {
    base_url: '<?= base_url() ?>',
    search_city: '<?= $_SESSION['search_city'] ?>'
  }
</script>
<script type="text/javascript" src="<?= base_url();?>js/external.js"></script>

Than content of your js became something like this:

$(document).ready(function(){
  // I assume that not using search_city in your sample code
  // and some syntax errors, is just by mistake...
  $('#update').click(function(){
  var tableVal={search_city:Settings.search_city};
  $.post(Settings.base_url+'/project_detail/pub',
    {'tableVal':tableVal},
    function(message){
      console.log(message);
    })
  })
})
Oid answered 31/1, 2012 at 16:49 Comment(3)
what happen if I use include('external.js.php')?Touching
Than your js will be inlined and processed. You'll need to surround it with script tag and it'll be okOid
is it possible to store the value of javascript vars in php vars inside the javascript code block?Christchurch
T
2

quite a common thing to want to do, just rename your js file to "external.js.php" (i use that method, but as long as it ends in php it doesn't matter what you use really) then just change the src url in your script tags and away you go.

Dont forget you may need to include function and config files into the javascript for that base_url() function to work.

Tammitammie answered 31/1, 2012 at 16:29 Comment(0)
R
2

Unless you need php for a lot of things in your js file, I'd suggest you don't do as mentioned above and not rename your js file to php to have it parsed. JS files are best served as static.

One thing you can do is have a script at the top of your php document where you assign your base_url variable as a global to be used by all your js:

In your page, before including any js

<script type="text/javascript">var base_url = "<?= base_url();?>";</script>
<script type="text/javascript" src="<?= base_url();?>js/external.js"></script>

In your js file

$(document).ready(function(){

    $('#update').click(function(){
    var tableVal={};
    // a bit of php code I need in JS
    var search_city=<?php echo $_SESSION['search_city'];?>';
    $.post(base_url+'/project_detail/pub', {'tableVal':tableVal},function(message)

        })
    })
})
Rapparee answered 31/1, 2012 at 16:39 Comment(2)
thanks for the help. As Juicy mentioned. There is still php code in js file. +1 though.Touching
agreeed. this is good way without loosing any performance. declaring variables with php values in it and then use those variables in js filesDerision
U
1

I believe it is possible, but as Brian mentioned you have to let the preprocessor know it needs to process it. You can either tell it to use php to handle .js files (Not recommended) or simply use a .php file for your javascript, then use:

<script type="text/javascript" src="<?= base_url();?>js/external.php"></script>

This should be okay because the mime type is still javascript so it will be interpreted that way. I've never actually tried this, so it is a guess, but I believe it should work.

Unprincipled answered 31/1, 2012 at 16:30 Comment(0)
C
0

Just a quick idea, that could help some people:

I think (never tried) there is also a way to ask the web server (Apache, etc) to let JS files be handled as PHP content.

Advantages:

  • No need to rename your JS files to .js.php
  • Takes advantage of caching
  • Can be applied only to a specific folder (not to every JS file of your website)

Withdraws:

  • Do not forget that those "php" files are "cached" somewhere, so don't rely on the fact that files are generated every time.
  • Server resources: as said in other answers, make sure to use such a trick only when it's really not possible to put PHP code outside of the JS files (using ajax queries for instance), or on files that don't load the server too much.
Cornstarch answered 27/7, 2015 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.