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.
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.
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);
})
})
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With