Citer
Citer

Reputation: 13

How can i set a global variable value in one function and access it through another in codeigniter?

I'm currently creating an app with Codeigniter and i came up with this issue (and it's not the first time to be honest).

What i want is to set a value in a global variable in function "foo()" and the access it through function "bar" (which is called through ajax call from client side).

In short, i want this variable to be full when the user has visited the page (sth like a session).

Here's an example code of my controller and what i'm trying to achieve:

class Groups extends CI_Controller{
  private $page_id;

  public function foo($slug = FALSE){
   $this->load->model('some_model');
   $info = $this->some_model->get_info($slug);
   $this->page_id = $info['page_id'];
  }

  public function bar(){
   $this->load->model('some_model');

   $info = $this->some_model->get_some_other_info($this->page_id);

   //Some code in here

  }
}

Any suggestions or best practices on achieve that?

I've tried searching the internet on that but i couldn't find something to start with. So if you have any suggestions on where to look at, feel free to do it!

Thanks

Upvotes: 1

Views: 51

Answers (1)

Mikeyhun
Mikeyhun

Reputation: 256

If i understand it right you will have 2 calls. One will be at page load where you want to store something and after that there will be an ajax call that will retrieve what you have stored. Because the 2 script loads are different you can only do it by storing the data to one of them: database/session/cookie/html session or localstorage.

Can't say anything about best practice because i dont know what you want to store and for how long so need a bit more info about your code (im guessing you want to store the "page_id"?).

Upvotes: 1

Related Questions