Welcome Guest, Not a member yet? Register   Sign In
External Javascript
#1

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???
Reply
#2

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
Reply
#3

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

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

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.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#6

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.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB