1

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();
}
7
  • Which error do you get? Can you place it here please? Commented Jul 30, 2013 at 16:17
  • PHP Fatal error: Call to undefined method CI_Loader::get_jcrop_ini() in C:\inetpub\d..\application\views\includes\header.php on line 81 Commented Jul 30, 2013 at 16:31
  • 1
    That is simple then... controller methods are not passed over to the view! You can create a helper function in the application/helpers/ folder that can be called in the view! Commented Jul 30, 2013 at 16:36
  • I've created and loaded a helper but I get errors using $this in the helper. function get_jcrop_ini() { $this->output->set_header('Content-type: text/javascript'); $data['load_jcrop_api'] = FALSE; $this->load->view('jcrop_ini',$data); } Commented Jul 30, 2013 at 16:50
  • I wrote a snippet to embed JavaScript files an internal code into views and manqging them inside of controllers. It could be helpful: gist.github.com/HashemQolami/5994689 Commented Jul 30, 2013 at 17:02

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm familiar with that technique and having given it more thought I think that will work fine for me. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.