CodeIgniter Forums

Full Version: Global variable in a class not working (using Ajax)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]mvdg27[/eluser]
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:

Code:
class Justtesting extends Controller {

  var $my_global_var;

    function Justtesting() {
        parent::Controller();
        $this->xajax->registerFunction(array('foo1',&$this,'foo1'));
        $this->xajax->registerFunction(array('foo2',&$this,'foo2'));
        $this->objResponse = new xajaxResponse();
        $this->xajax->processRequest();
    }

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

    function foo2() {
        $this->objResponse->alert($this->my_global_var);
        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

El Forum

[eluser]Lone[/eluser]
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.

El Forum

[eluser]mvdg27[/eluser]
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

El Forum

[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 ?
Thanks

El Forum

[eluser]mvdg27[/eluser]
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:

Code:
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.

Michiel