Question

I have a javascript script that changes an image's src when clicked. When I had the same application in pure php without Codeigniter I simply had the images' src be something like "images/image_name" where images was the images folder, but now I'm using Codeigniter I don't know how to do it. I can't use php inside the JS script obviously so can't use the base_url() or site_url() functions or anything, so I suppose only the absolute path would work. And my images are in an images folder that's inside an assets folder which is at the root (i.e. at the same level as the Application, System and User_guide folders). So what should the images' src be? Thanks.

Was it helpful?

Solution

You can use php code inside script.

<script>
     var imgSrc="<?php echo base_url('assets/images/image_name.jpg'); ?>";
</script>

Or you can also declare a global variable in header file to store base path.

<script>
     basePath='http://www.yourdomain.com/';
</script>

and it can be used as

var imgSrc=basePath+"assets/images/image_name.jpg"; 

OTHER TIPS

in addition to piyush's answer, I need to mention something that will help to use site_url() & base_url() properly.

site_url("controller/method/args") == base_url() + $config['index_page'] + /controller/method/args. You should use this to access pages.(Reference)

base_url("public/img/logo.png") == base_url() + /public/img/logo.png. You should use this to access resources such as images, stylesheets etc.(Reference)

Main difference between both functions is this part $config['index_page']. If you have already removed the $config['index_page'] from the config.php and you are using .htaccess to rewrite the URLs, then both function will result the same. But it is a best practice to use the correct function for the correct purposes.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top