Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use PHP code in external Javascript file

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.

like image 977
FlyingCat Avatar asked Jan 31 '12 16:01

FlyingCat


2 Answers

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);
    })
  })
})
like image 200
Juicy Scripter Avatar answered Sep 19 '22 18:09

Juicy Scripter


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.

like image 25
Lee Avatar answered Sep 21 '22 18:09

Lee