0

i want to use base url in javascript file using codeigniter function base_url()

i am doing it as below but this is not working ,

$('.toggleimg').attr('src','<?=base_url?>assets/front/img/sidebar1.jpg');

Please helpe me how can i make it work in a js file .

Sikander
  • 2,799
  • 12
  • 48
  • 100

3 Answers3

3

On your .php file, outside the <?php ... ?> tags, define base_url with php :

<script type="text/javascript">
    var base_url = <?php echo base_url() ?>;
</script>
<script src="your-js-file.js" ></script>

then you could use base_url variable on your your-js-file.js javascript file :

$('.toggleimg').attr('src', base_url + 'assets/front/img/sidebar1.jpg');
Hasta Dhana
  • 4,699
  • 7
  • 17
  • 26
1

Probably you have this piece of code in a ".js" file. The PHP code <?=base_url?> will work only in a .php file. See this question for an answer to get base url in js.

  • Frankly the linked answer here is the best option if all you need is the base url. If you really need to get this or other info from PHP, your options are AJAX or a variation of my answer. – Kyusa Mar 13 '18 at 02:00
0

You cannot execute PHP code inside of javascript, you could assign the base url to a variable and then call that in your js.

Although I don't see why you would need to assign the base url through a variable as surely this will never change?