codeigniter load view specific javascript
codeigniter, php
Solution
You can send which js to load as a variable. Example is here;
Sample controller
class mypage extends CI_Controller{
public function index(){
$data['js_to_load']="index.js";
$this->load->view('header',$data);
$this->load->view('my_html_page');
}
public function second_page(){
$data['js_to_load']='second.js';
$this->load->view('header',$data);
$this->load->view('my_second_html_page');
}
}
header.php - View file
<!-- Needed html code here -->
<? if ($js_to_load != '') : ?>
<script type="text/javascript" src="assets/js/<?=$js_to_load;?>">
<? endif;?>
<!-- Other html code here -->
Whats happening?
We are setting the js file into $data variable, and passing the $data variable to header. In header file we are checking if js_to_load is set? If yes, we are including the js file.
Also you can pass multi js files by using arrays.
Sample controller
class mypage extends CI_Controller{
public function index(){
$data['js_to_load']=array("index.js","index1.js","index2.js");
$this->load->view('header',$data);
$this->load->view('my_html_page');
}
public function second_page(){
$data['js_to_load']=array("second.js","second2.js","second2.js");
$this->load->view('header',$data);
$this->load->view('my_second_html_page');
}
}
header.php - View file
<!-- Needed html code here -->
<? if (is_array($js_to_load)) : ?>
<? foreach ($js_to_load as $row):
<script type="text/javascript" src="assets/js/<?=$row;?>">
<?endforeach;?>
<? endif;?>
<!-- Other html code here -->
Problem
I have a register view file on which there is a very big form. Hence I plan to use a form wizard plugin along with the jquery form validation plugin. I only want these scripts loaded on specific pages. How do I do this ? Here is my controller method. ``` public function index(){ $data['title'] = "Register"; $this->load->view("site_header", $data); $this->load->view("site_nav"); $this->load->view("content_register"); $this->load->view("site_footer"); } ``` I saw a similar post on stackoverflow here but I don't understand what to do. Please help.