user7149801
user7149801

Reputation: 65

How to dynamic a url with codeigniter base_url() inside js file

I want to load a url with dynamically inside js file. i used below code inside the head.js file but it's not getting the url. if i use statically then it works nicely. I can't find my problem.

head.js(<?php echo base_url(); ?>"assets/js/newsticker/jquery.newsTicker.js", function() {
    var nt_title = $('#nt-title').newsTicker({
        row_height: 18,
        max_rows: 1,
        duration: 5000,
        pauseOnHover: 0
    });
});

Upvotes: 1

Views: 2579

Answers (2)

Zinc
Zinc

Reputation: 385

you can't use <?php echo base_url(); ?> on JavaScript file.

If you want to get the url dynamically, you can use window.location.origin

var url = window.location.origin;

Variable url will print like base_url : https://stackoverflow.com

Subdomain will print like : https://subdomain.stackoverflow.com

So, just changes your <?php echo base_url(); ?> into url+ and add / before assets, like :

head.js(url+"/assets/js/newsticker/jquery.newsTicker.js", function() {
    var nt_title = $('#nt-title').newsTicker({
        row_height: 18,
        max_rows: 1,
        duration: 5000,
        pauseOnHover: 0
    });
});

Hope this help.

Upvotes: 2

Hikmat Sijapati
Hikmat Sijapati

Reputation: 6994

If you want to get base_url() in pure JS file.Following may be a right way...

1.In html (PHP) create a input field of hidden type with value base_url.As

<input type="hidden" id="url" value="<?php echo base_url();?>">

2.Then in your Pure JS file such as head.js.Get base_url as below.

<script>
var base_url = $("#url").val();//it gives base_url
head.js(base_url+"assets/js/newsticker/jquery.newsTicker.js", function() {
    var nt_title = $('#nt-title').newsTicker({
        row_height: 18,
        max_rows: 1,
        duration: 5000,
        pauseOnHover: 0
    });
});
</script>

NOTE: In codeigniter don't forget to load url helper for use of base_url().

Upvotes: 2

Related Questions