0

I'm using the CodeIgniter framework. I load a main view, which contains several tabs, which load other views in a <div> via AJAX. My controller class looks like this:

class MainController extends MY_Controller
    function main($id=0)
    {
        $this->load->model('main_model');
        $this->data['info'] = $this->main_model->foo($id);
        $this->load->view('main_view', $this->data);
    }

    function tab1()
    {
        $this->load->view('tab1_view', $this->data);
    }

}

I load the main page by calling mywebapp/main/123. The id can be used in the main method and in the main_view. But when I click on the tab, I want to use id in the <div> in main_view as well. What's the best way to do this? Maybe any way to make this variable global for every method in the controller?

I load the tab using jQuery:

$("#div").load(mywebapp/tab1);
tereško
  • 58,060
  • 25
  • 98
  • 150
bausa
  • 111
  • 2
  • 9

1 Answers1

1

Use __construct()

class MainController extends MY_Controller

protected $_id;

    public function __construct()
{
        $this->_id = $this->uri->segment(3);
}

    function main()
    {
        $this->load->model('main_model');
        $this->data['info'] = $this->main_model->foo($this->_id);
        $this->load->view('main_view', $this->data);
    }

    function tab1()
    {
        //available here too
        echo $this->_id;
        $this->load->view('tab1_view', $this->data);
    }
}

Alternately you could change this to use: $this->uri->uri_to_assoc(n) which are key value pairs after /method/controller/key/value/key2/value2

Example:

/user/search/name/joe/location/UK/gender/male

[array]
(
    'name' => 'joe'
    'location'  => 'UK'
    'gender'    => 'male'
)
wesside
  • 5,622
  • 5
  • 30
  • 35
  • this sadly doesn't work for me. When I load a 'subview' with $("div").load(mywebapp/tab1)` the `MainController` gets loaded again and `$this->_id` gets overritten empty (`$this->uri->segment(2)` is tab1) – bausa Sep 20 '12 at 01:50
  • so pass it. $('div').load('mywebapp/tab1?somevar==$this->_id;?>'); If some var exists, overwrite $this->_id – wesside Sep 20 '12 at 01:51