1

For code requirement and security purpose I am calling image using its path inside main.js file, but for normal php (without framework) it works in this way but problem is that I am using Codeigniter and in codeigniter you can call using base_url() in php file but here image is inside js file so my question is how to specify image path inside js with codeigniter.

var modifytop={

controlHTML: '<img src="assets/img/arrow.png" style="width:40px; height:40px" />',
anchorkeyword: '#top',

 }
1
  • You can also prepend path with slash which will force browser to read location from the root i.e. /assets/img/arrow.png. Commented Feb 2, 2018 at 17:07

1 Answer 1

1

Since JS cannot identify the PHP, PHP code will not execute.

So declare the base_url() in your HTML file.

<html>
<body>
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
//your rest of js source links
</body>
</html>

Then use the base_url variable in the JS file.

var modifytop={

controlHTML: '<img src="'+base_url+'"assets/img/arrow.png" style="width:40px; height:40px" />',
anchorkeyword: '#top',

 }

Set the base_url in config file as below

$config['base_url'] = "http://localhost/your-project-name/";
Sign up to request clarification or add additional context in comments.

12 Comments

this is fine since quotes are illegal in a url, but most of the time it's safer to json encode stuff that you're passing to javascript.. myvar = <?php echo json_encode($myvar); ?> (no surrounding quotes).
also, you have some funky quotes in your controlHTML string
Surrounding codes are required. I have used earlier like you mentioned. But it gives me an error.
if you encode it like i suggested the quotes are not required, in fact, the quotes will break it. when you said you fixed it i thought you meant the json encode, not the string.. that's why i deleted the comment and upvoted.. all good, it works as is
Did you display it in the console?? If displayed what you are getting??
|

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.