1

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:

  1. 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 index foo.
0

1 Answer 1

4

jstest.js in system/sources/js/ directory made an ajax call to ajaxtest.php.

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 sessions­Docs.

Sign up to request clarification or add additional context in comments.

5 Comments

Spot on. A possible solution would be to store the data in $_SESSION. Look up the documentation for session handling in PHP
Session needs configuration and has pre-conditions. Actually they will work in your case however, you need to ensure that the client is using the appropriate session identifier with each request. Add the session id to your ajax request.
@NeigylR.Noval $_SESSION and $GLOBALS are not interchangeable.
See edit. Sessions does not work either. Php still cannot determine the index 'foo'.
If you already have set that session value in the original request, but you can't obtain it in a later request, then your session is broken. You need to fix it first. It might just be that changing the variable name in two places is not enough. Please see the link to sessions PHP manual in the answer. Ensure that you pass the session id with your AJAX request: php.net/manual/en/session.idpassing.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.