[php] How to call codeigniter controller function from view

How to call codeigniter controller function from view? When i call the function in a controller, get a 404 page.

This question is related to php codeigniter

The answer is


I know this is bad.. But I have been in hard situation where it is impossible to put this back to controller or model.

My solution is to call a function on model. It can be do inside a view. But you have to make sure the model has been loaded to your controller first.

Say your model main_model, you can call function on the model like this on your view : $this->main_model->your_function();

Hope this help. :)


class MY_Controller extends CI_Controller {

    public $CI = NULL;

    public function __construct() {
        parent::__construct();
        $this->CI = & get_instance();
    }

    public function yourMethod() {

    }

}

// in view just call
$this->CI->yourMethod();

Go to the top of your View code and do it like this :

  <?php
     $this->load->model('MyModelName');
     $MyFunctionReturnValue = $this->MyModelName->MyFunctionName($param));
?>

<div class="row">
    Your HTML CODE
</div>

We can also pass controller function as variable in the view page.

class My_controller extends CI_Controller {
    public function index() {
           $data['val']=3;
           $data['square']=function($val){
                               return $val*$val;
                                   };
    $this->load->view('my-view',$data);
}
}

In the view page

<p>Square of <?=$val?>
   <?php 
     echo $square($val); 
   ?>
</p>

The output is 9


One idea i can give is,

Call that function in controller itself and return value to view file. Like,

class Business extends CI_Controller {
    public function index() {
            $data['css'] = 'profile';

            $data['cur_url'] = $this->getCurrURL(); // the function called and store val
            $this->load->view("home_view",$data);
     }
     function getCurrURL() {
                $currURL='http://'.$_SERVER['HTTP_HOST'].'/'.ltrim($_SERVER['REQUEST_URI'],'/').'';
            return $currURL;
     }

}

in view(home_view.php) use that variable. Like,

echo $cur_url;

it is quite simple just have the function correctly written in the controller class and use a tag to specify the controller class and method name, or any other neccessary parameter..

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Iris extends CI_Controller {
    function __construct(){
        parent::__construct();
        $this->load->model('script');
        $this->load->model('alert');

    }public function pledge_ph(){
        $this->script->phpledge();
    }
}
?>

This is the controller class Iris.php and the model class with the function pointed to from the controller class.

<?php 
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Script extends CI_Model {
    public function __construct() {
        parent::__construct();
        // Your own constructor code
    }public function ghpledge(){
        $gh_id = uniqid(rand(1,11));
        $date=date("y-m-d");
        $gh_member = $_SESSION['member_id'];
        $amount= 10000;
        $data = array(
            'gh_id'=> $gh_id,
            'gh_member'=> $gh_member,
            'amount'=> $amount,
            'date'=> $date
        );
        $this->db->insert('iris_gh',$data);
    } 
}
?>

On the view instead of a button just use the anchor link with the controller name and method name.

<html>
    <head></head>
    <body>
        <a href="<?php echo base_url(); ?>index.php/iris/pledge_ph" class="btn btn-success">PLEDGE PH</a>
    </body>
</html>

I had this same issue , but after a couple of research I fond it out it's quite simple to do,

Locate this URL in your Codeigniter project: application/helpers/util_helper.php

add this below code

//you can define any kind of function but I have queried database in my case

//check if the function exist
 if (!function_exists('yourfunctionname')) {
    function yourfunctionname($param (if neccesary)) {
        
        //get the instance
        $ci = & get_instance();
    
        // write your query with the instance class

        $data =  $ci->db->select('*');
        $data =  $ci->db->from('table');  
        $data =  $ci->db->where('something', 'something');

        //you can return anythting

        $data =  $ci->db->get()->num_rows(); 

        if ($data > 0) {
            return $data;
        }  else {
            return 0;
        }  
    }
}

views cannot call controller functions.


You can call controller function from view in the following way:

Controller:

public function read() {
    $object['controller'] = $this; 
    $this->load->view('read', $object);
}

View:

// to call controller function from view, do
$controller->myOtherFunct();

You can call a controller function with AJAX on your view. In this case, I'm using the jQuery library to make the call.

<script type="text/javascript">
    $.ajax({
            url: "<?=site_url("controller/function")?>",
            type: "post", // To protect sensitive data
            data: {
               ajax:true,
               variableX: "string",
               variableY: 25
               //and any other variables you want to pass via POST
                   },
            success:function(response){
            // Handle the response object
            }
        });
</script>

This way you can create portions of code (modules) and reload them the AJAX method in a HTML container.


Try this one.

Add this code in Your View file

$CI     = & get_instance();
$result = $CI->FindFurnishName($pera);

Add code in Your controller File

public function FindFurnishName($furnish_filter)

{

$FindFurnishName        = $this->index_modal->FindFurnishName($furnish_filter);  
$FindFurnishName_val    = '';
foreach($FindFurnishName as $AllRea)
{
    $FindFurnishName_val  .= ",".$AllRea->name;
}
return ltrim($FindFurnishName_val,',');

}

where

  1. FindFurnishName is name of function which is define in Your Controller.
  2. $pera is a option ( as your need).

if you need to call a controller from a view, maybe to load a partial view, you thinking as modular programming, and you should implement HMVC structure in lieu of plane MVC. CodeIgniter didnt implement HMVC natively, but you can use this useful library in order to implement HMVC. https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc

after setup remember:that all your controllers should extends from MX_Controller in order to using this feature.


I would like to answer this question as this comes all times up in searches --

You can call a controller method in view, but please note that this is not a good practice in any MVC including codeigniter.

Your controller may be like below class --

<?php
    class VCI_Controller extends CI_Controller {
    ....
    ....
    function abc($id){
       return $id ;
    }

    }
?>

Now You can call this function in view files as below --
<?php
    $CI =& get_instance();
    $CI->abc($id) ;

?>