First, here are the hierarchy of files:
system/
...index.php
...core/
.......MasterView.php
.......Test.php
...sources/
.......ajax/
............ajaxtest.php
.......js/
............jstest.js
and so on.
index.php includes Test.php.
Test.php contains these lines:
$GLOBALS['foo'] = 'foo'; // note 1
require(ROOT.'/core/MasterView.php'); // render master view.
MasterView.php contains simple html tags but calls on jstest.js in system/sources/js/ directory.
jstest.js in system/sources/js/ directory made an ajax call to ajaxtest.php.
ajaxtest.php in system/sources/ajax/ directory contains this line:
echo $GLOBALS['foo']; // note 2
After running index.php on browser, the following error occurs:
Undefined index: foo in ...ajax\ajaxtest.php ...
particularly pointing to note 2 line. My question is, why does php does not recognize foo index when I have defined it on note 1 line before calling MasterView.php?
PS: I know the above method is not the best way to do it but I only give it as an illustration to my problem.
EDIT:
- I’ve tried using
$_SESSION['foo']instead of$GLOBALS['foo']in both files just to mention one solution I’ve tried. Same error occurs. Php does not recognize the indexfoo.
Global variables are global to the same request only. If you connect files with an AJAX request in between, the global variable is not available because AJAX will create a new request.
You can share data across multiple requests by creating some sort of Server Session State by using cookies, a database or PHP sessionsDocs.