Use PHP code in external Javascript file

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="https://stackoverflow.com/questions/9083089/<?= 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);
    })
  })
})

Leave a Comment