1

I was trying to call "base_url()" inside of an external .js file. my 'test.js' file path is "js/test.js".

my test.js code was:

    function download(s){
        var w=window.open('<?php base_url(); ?>home/download?f='+s+'.ogg','Download','height=100,width=100');
    }

And I linked that file(my js file is working fine when trying simple JavaScript codes) :

<script src="<?php echo base_url(); ?>js/test.js" type="text/javascript"></script>

But that always said that the access was denied and asked for server permission.

I tried 'site_url()' too, even I tried just an echo "hello" in 'download' function but those didn't work. But when I add that code inside of header.php view file like:

<script type="text/javascript">
    function download(s){
        var w=window.open('<?php base_url(); ?>home/download?f='+s+'.ogg','Download','height=100,width=100');
    }
</script>

Then that worked.

And in case of external CSS when I write:

background:url('<?php base_url(); ?>images/side.png');

That doesn't work. But if I write:

background:url('../images/side.png');

Then that works.

So how can I call "base_url()" inside of external .js file and .css file ?

5
  • I'm a bit confused. Is that <script> block being called from within a PHP file? PHP code only gets executed from known php files. Ie. *.php or *.inc files (given your installation is stock) Commented Aug 20, 2013 at 0:40
  • if I use javascript block in a php file only then base_url works. Commented Aug 20, 2013 at 0:44
  • you could make js/css files into php w/header of Content-type: text/javascript to make it a css/js Commented Aug 20, 2013 at 0:47
  • Yeah, or you can cheat it and just put it in a php file, but thats a tad bit risky. Commented Aug 20, 2013 at 0:48
  • got it.so I will put those particular code blocks in my header.php. Commented Aug 20, 2013 at 0:54

2 Answers 2

2

You can't call base_url() in a javascript / css file.

You need to put a relative path in these js/css files. PHP scripts aren't aren't run unless they're in a .php file.

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

2 Comments

so would I have to use that particular css or js code in header.php file ?
Yea thats exactly how i'd get around your problem.
0

For Using This Solution Just Keep in mind that you have to put the Script tag before the external js script.

<script type="text/javascript">
  var baseURL = "<?php echo base_url(); ?>";
</script>

Now Use baseURL variable in that external js.

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.