Use your Site URL or Base URL in Javascript functions
When writing AJAX applications with CodeIgniter, you usually want to post to a controller class by using Javascript functions. For example, if you are using jQuery for posting a form or loading back a page using an AJAX style, then you need to call the Controller class from your jQuery code.
The way I usually do that is the following way:
I usually create a javascript object called CI, and make it globally accessible. Usually I place that variable in my header file (view), so it is defined anytime a page is displayed.
<script type="text/javascript">
<!--
var CI = {
'base_url': '<?php echo base_url(); ?>',
'another': '<?php echo '' ?>',
'another2': '<?php echo '' ?>'
};
-->
</script>
Then, anytime you need to use your base_url(), site_url() or whatever you need (originally accessible via PHP) in a Javascript functions, you can simple call your CI.base_url
This way is very accessible so you don’t need to embed PHP function calls between your Javascript pieces of code.
Moreover, if you have external .js (javascript files), then you can easily handle these PHP or CodeIgniter variables.
So, how to use your Javascript CI variable?
Imagine you are using jQuery for your AJAX calls. Here, instead of using the <?php echo base_url() ?> we are willing to use our new CI object, as follows:
$.ajax({
url: CI.base_url + 'time/ajax_clock',
async:true,
global: true,
ifModified: false,
processData:true,
success: function(data){
},
type: "POST"
});
Obviously you can extend your Javascript CI object using any other variable you may require in your application.
Related posts:





I use base tag for this.
DominixZ
15 Aug 09 at 12:19 pm
Usuing a global JavaScript object with helpful CI values is a pretty good idea. I can see myself adding that funcionality into my project. Great idea. One thing, though, if the element you’re interacting with has a standard non-Ajax way of executing, it’s usually better to use that item’s URL (href or action attrs) for the Ajax call so that if you need to make changes, you’re not making them in two places. Progressive enhancement is important depending on your project and audience. Your idea can be used for several reasons other than just ajax URLs as well, though.
Good post.
Kyle
19 Aug 09 at 9:41 am
Hi Kyle, exactly. It can be used for several reasons other than just AJAX. In my past experience, I remember I used it mostly for AJAX calls as described in this article, but probably other people have different needs and then the approach can be valid, too. Thanks for noticing that.
admin
19 Aug 09 at 10:18 am
Sometimes I needed PHP language variables in JavaScript files. With this method I can now set up any variable to be accessible by other JavaScript files.
Thanks!
Istvan
17 Sep 09 at 6:44 am