CodeIgniter Forums
Loading servers variables to the javascripts files in CodeIgniter - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: Loading servers variables to the javascripts files in CodeIgniter (/showthread.php?tid=20367)



Loading servers variables to the javascripts files in CodeIgniter - El Forum - 07-07-2009

[eluser]Unknown[/eluser]
One of the motives why I created the article "Virtuals formats hooks for CodeIgniter" was for creating the feature of this article. Imagine you have some variables you wanna to load into your scripts but this values changes depending from data manipulated from the serverside (in our case a CodeIgniter application), and we don’t like to put this variables between [removed][removed] tags, because this is ugly, and a non good programming practice as the YSlow Firefox plugin rule says: Yahoo Developers. So what I do is to build a new Controller called "configs" which in the constructor builds me to variables I need for my ExtJS based application. This is the code:


Code:
class Configs extends Controller{

function Configs()
{
parent::Controller();
$this->load->helper('url');
$this->globals['base_url']=base_url();
$this->globals['scripts_base']=$this->globals['base_url'].'system/public/scripts/';
}

function index()
{
echo "This hosts dynamics virtual files for global vars";                
}

function global_vars($archive)
{
switch($this->router->format)
{
case "js": //If you are asking for a javascript file
foreach($this->$archive as $key_name=>$key_value)
echo "var $key_name='$key_value';\n";
}
}
}


So in your view file you could put:
[removed][removed] and keep the HTML code optimized and clean, and this fake script file adapts to the server configuration because is in fact a server script. It's very useful to those like me who develops application with javascript libraries like ExtJS, JQuery, Dojo and his friends Wink
Thanks to anybody who reads this article, I hope it would be useful for you. I will thanks feedback to me.
Greetings, Eliecer (EliuX) Hdz. Garbey.


Loading servers variables to the javascripts files in CodeIgniter - El Forum - 07-07-2009

[eluser]Cro_Crx[/eluser]
This works fine if your variables are simple. If you want to pass objects however you will need to use JSON.