Welcome Guest, Not a member yet? Register   Sign In
Global variable in a class not working (using Ajax)

Hi guys,

I'm not sure if I made a coding error, or if CI handles global vars in a class differently or that using Ajax changes things, but somehow I'm not able to share a variable across functions in the same class.

My code:

class Justtesting extends Controller {

  var $my_global_var;

    function Justtesting() {
        $this->objResponse = new xajaxResponse();

    function foo1($var) {
        $this->my_global_var = $var;
        // code here ...
        return $this->objResponse;

    function foo2() {
        return $this->objResponse;


First the function foo1 is called and it successfully alerts the my_global_var. After, the function foo2 is called, but then my_global_var is not available anymore ..

Anyone have an idea why?

Cheers, Michiel

The variable is only persistant in the controller for each http request.

1. Access http://domain.com/justtesting/foo1
- Sets var
- Uses var

2. Access http://domain.com/justtesting/foo2
- Uses var

Hope this makes some sense (you may look more into how objects are used in PHP/CI) - to cure the issue you could set the var in a model or library and access from there.

Ah yes .. that makes sense! I managed now by adding the variable with my javascript ajax call. So the function foo2 now receives an extra variable and this works fine!

Thanks for clearing this up!

Cheers, Michiel

[eluser]Đỗ Thanh Tùng[/eluser]
Hi there.
I have same problem like mvdg27.
I'm new in CodeIgniter. Can somebody post an example that fix that problem ?

Well, it's as simple as this: instead of setting a global var in your script ($this->my_var = 'my value'), you have to make sure that every function accepts the var as a parameter:

function foo($var1, $var2, $var3, $my_var) {


So when you are making your ajax calls, be sure to either hard code, or print the value of your var in the javascript handler.

The most important thing to remember is that, each ajax call, loads a complete new instance of the controller. Hence there is no memory in the form of global variable available.

Hope that helps.


Theme © iAndrew 2016 - Forum software by © MyBB