Michael Grigsby
Michael Grigsby

Reputation: 12163

Calling a view within a view not working properly

<script src="<?php echo site_url('bootstrapper/jqTimer'); ?>"></script>

So I've tried to call the controller below using the script above but I get error not found. Any ideas as to why this method is not working?

function jqTimer() {
    $this->load->view("jquery.timers.js");
}

Upvotes: 0

Views: 87

Answers (3)

Mudshark
Mudshark

Reputation: 3253

You're looking to echo out a link to the js, not echo out the js itself. You could create a MY_Controller in the core folder which extends CI_Controller, in which:

function jqTimer() {
  return site_url("jquery.timers.js");
}

Then, in any other controller (which extends MY_controller) you'd go:

$data['js_timer'] = $this->jqTimer();
/* proceed to load main view with $data */

View:

<script src="<?php echo $js_timer; ?>"></script>

This is DRY in that, should you decide to use a different js timer plugin, you need to replace it in one place only: the MY_Controller class (as opposed to every view file).

Still, a bit of an odd way of doing things...

Upvotes: 0

Fad
Fad

Reputation: 9858

I don't see any reason why you should create a function in the controller just to load a javascript file. The base_url() function can already do what you want.

<script src="<?php echo base_url('path/to/jquery.timer.js'); ?>"></script>

Have a look at the documentation for the URL helper

Upvotes: 0

swatkins
swatkins

Reputation: 13630

When loading javascript with a <script> tag, the src attribute is expecting a file name to a js file. You're giving it a path to a controller method in your CI install.

What you need to do is put the jquery.timers.js file in the public_html folder and access it from there:

// assuming you have the script in a [javascripts] folder inside [public_html]
<script src="<?php echo site_url('javascripts/jquery.timers.js'); ?>"></script>

If you'd prefer to load your javascript through views, then you need to do this instead:

<script><?php echo $this->load->view("jquery.timers.js", "", TRUE); ?></script>

This will echo out the contents of the view file between the <script> tags for embedded javascript. (passing TRUE as the third parameter returns the content of the file, so you can echo it out)

Upvotes: 2

Related Questions