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 .

3 Answers 3

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');
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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

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.