1

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
    });
});
5
  • You can use php only in .php file not in .js file . What is your Base url and what url you get by / + assets/ Commented Jan 11, 2017 at 16:45
  • if the filename is head.js this would not work, you have to name your file head.php Commented Jan 11, 2017 at 16:45
  • if i rename head.js file as head.php then will it be worked for js code??? Commented Jan 11, 2017 at 17:16
  • stackoverflow.com/questions/36051588/… Commented Jan 11, 2017 at 20:31
  • @user7149801 try as below. Commented Jan 12, 2017 at 1:48

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.