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 requirephp
)
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);
})
})
})
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.
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)
})
})
})
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.