How to use CodeIgniter config values inside Mootools
I am using Mootools with most of my CodeIgniter projects, and I often have to use site_url() and base_url() inside my Mootools script especially when I’m dealing with ajax uploading (in order to refresh picture thumbnails for example).
That’s why I have implemented a very simple way to use CodeIgniter‘s config values in a Mootools script :
Setting up the CodeIgniter controller
The point is to generate a JavaScript file with a CodeIgniter controller.
- Create a new PHP file called mootools.php in system/application/controllers/
- Copy / Paste the code below inside mootools.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php class Mootools extends Controller { function Mootools() { parent::Controller(); $this->load->helper('url'); } function index() { header('Content-type: application/javascript'); $js = " var site_url = '" . site_url() . "'; var base_url = '" . base_url() ."'; "; echo($js); } } /* End of file mootools.php */ /* Location: ./system/application/controllers/mootools.php */ |
Adding the JavaScript file to your header
Next, we have to add the JavaScript file generated by CI inside our HTML header, just add this line after the mootools inclusion in your header view:
1 |
<script src="<?php echo site_url('mootools') ?>" type="text/javascript"></script> |
Testing
Here is a simple testing script that write your base_url() and site_url() value in two H2 tags.
The CodeIgniter view to load:
1 2 3 4 5 6 7 8 9 10 11 12 |
<html> <head> <title>Mootools / CodeIgniter integration by nukium.com</title> <script src="<?php echo base_url() ?>js/mootools-1.2.2-core-yc.js" type="text/javascript"></script> <script src="<?php echo site_url('mootools') ?>" type="text/javascript"></script> <script src="<?php echo base_url() ?>js/demo.js" type="text/javascript"></script> </head> <body> <h2 id="demo-site_url"></h2> <h2 id="demo-base_url"></h2> </body> </html> |
The JavaScript testing file:
- Create a new file in /js called demo.js
- Copy / Paste the code below inside demo.js
1 2 3 4 5 6 |
window.addEvent('domready', function(){ $('demo-site_url').set('text', site_url); $('demo-base_url').set('text', base_url); }); |
Then just load the view inside a controller to see your config values printed in the two H2 tags 😉
PS: Don’t forget to add the mootools core in the /js folder !