Paul Benbow
Paul Benbow

Reputation: 329

Codeigniter - how to include a dynamic javascript file in a view

I'm trying to include the following code block (which contains some dynamic values) in my header view if certain conditions are met.

<script src="<?php echo base_url();?>assets/jquery.Jcrop.js"></script>
<link rel="stylesheet"  href="<?php echo base_url();?>assets/jquery.Jcrop.css" />
<script type="text/javascript">
    <?php if (isset($load_jcrop_api) && $load_jcrop_api === TRUE) {?>
        // Javascript 1
    <?php } else { ?>
        // Javascript 2
    <?php } ?>
</script>

I've done some reading up and I started to try the following but I get an error trying to call this function from within a view so I'm a bit stuck on the best way to appoach this.

CONTROLLER

function get_jcrop_ini() {
    $this->output->set_header('Content-type: text/javascript');
    $data = array( 'messages' => $this->session->flashdata('message'));
    $this->load->view('jcrop_ini',$data);
}

VIEW

if (isset($load_jcrop) && $load_jcrop === TRUE) {
    $this->get_jcrop_ini();
}

Upvotes: 1

Views: 4534

Answers (1)

igasparetto
igasparetto

Reputation: 1146

Load the JS view in the controller and pass it over to the controller.

$jsview = $this->load->view('view_name', array(), true);

Note that the third parameter is set to true. That will return the view to you instead of outputting the view to the screen.

Then, pass it over to your main view.

$data['js'] = $jsview;

$this->load->view('mainview',$data);

That is a better MVC approach as the logic remains in the controller.

Upvotes: 1

Related Questions