[eluser]SitesByJoe[/eluser]
I wanted to share a cool technique I just cooked up to get CI Class data into external / unobtrusive javascript files.
I make alot of real estate-type websites which result in lots of javascript with google maps etc. I'd run into situations where I'd need top get dynamic address data that used in the CI environment into my javascripts. If you're using outside files how can you get the data in there?
I didn't want to have to generate javascript code using PHP...(too messy) I ended up putting the scripts into my page templates (code duplication - yuck!) I finally came up with another way just before deciding to put this in front of you all.
The concept: Take the external js files and put them in with my views so I can call them just like PHP views. Before scanning the code below - a couple disclaimers:
1. In the controller code I add a header to specify I'm sending javascript to the browser.
2. A couple values in the view file come from a custom config file I have set up.
3. The javascript in the view uses JQuery syntax.
You'll need a couple ingredients:
A controller:
Code:
class Javascripts extends Controller {
function Javascripts()
{
parent::Controller();
}
function _remap()
{
if($this->uri->segment(2))
{
$file_name = $this->uri->segment(2);
header("content-type: application/x-javascript");
$this->load->view('js/' . $file_name);
}
}
}
A view:
Code:
function mailbuild_form_check()
{
$.post("/contact/signup", {
'ajax' : true,
'<?=$this->config->item('mailbuild_name')?>' : $('#signup_name').val(),
'<?=$this->config->item('mailbuild_email')?>' : $('#signup_email').val()
}, function(data) {
$('<div id="signup_section">' + data + '</div>').modal();
$('#signup_section').focus();
});
return false;
}
Hopefully this concept in structure helps as its allowed me to do some major cleanup in my templates no matter how complex the javascript code is!