CodeIgniter Forums
External Javascript - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: External Javascript (/showthread.php?tid=76601)



External Javascript - 68thorby68 - 05-31-2020

Hi,
I am using CI4

My preferred way of using javascript/jquery is to use external .js files

Code:
<script src="<?php echo base_url('includes/common/js/myfunctions.js'); ?>" ></script>


rather than including the javascript/jquery in the page
Code:
$.ajax({
    type: "POST",
    processData: false, // important
    contentType: false, // important
    data: data,
    url: "<?= base_url('file/function'); ?>",
    dataType: "script",
    beforeSend: function() {
        $('.processing').show();
    },
    complete: function() {
        $('.processing').hide();
    },
    success: function (data) {
        alert(data);            
    },
    error: function(data) {
        alert('error '+data);
    },
});
Does codeigniter 4 address any of the obvious issues that would arise is if I was to use try and use codeigniter helpers like base_url() in an external js file???


RE: External Javascript - mjamilasfihani - 06-01-2020

Just try to use full url, it's an external js you cant do it. If you put the js script in your view, you can use it. But set it in controller


RE: External Javascript - dave friend - 06-01-2020

The PHP calls in an external js file won't be evaluated.


RE: External Javascript - 68thorby68 - 06-06-2020

Thanks for the replies. Was worth asking the question as i'm finding more and more good stuff in Ci4.


RE: External Javascript - InsiteFX - 06-06-2020

You can add it to the html head section like so.

Code:
<script type="text/javascript">
    var baseUrl = "<?php echo base_url();?>";
    // or if you need index.php
    var siteUrl = "<?php echo site_url();?>";
</script>

Now you can use it anywhere you like in jQuery.


RE: External Javascript - 68thorby68 - 06-09-2020

Thanks InsiteFX, This is probably a better solution for me as I can reuse the external script rather than duplicating it on a per page basis.