tags:

views:

735

answers:

2

I have one PHP script with a session variable, set like so:

$_SESSION['VAR1'] = "test"

Now, I am using AJAX via a jQuery-initiated POST request, and so I have a script named ajax.php which has all the required functions.

And when I try access my session variable (echo $_SESSION['VAR1']) in ajax.php, it produces nothing.

Does session does not work from AJAX requests?

+6  A: 

You need do this on every page that accesses the session before you access it:

session_start();

That means on both the page that sets the session variable and the AJAX page that tries to retrieve it. Both need to call session_start().

As long as the AJAX request calls a script in the same domain (and thus gets access to the session cookie) there is no reason why it couldn't get access to the session variables. An AJAX request after all is just another HTTP request.

cletus
I tried that but i am not getting any session variable in that page.I am ussing joomla on previous pages , so may that is destroying the session avriables once page laods
Mirage
+1  A: 

Make sure that the domain names for both pages (i.e. the AJAX container and the AJAX script are same). Here is an example:

http://mydomain.com/login.php           (set session variables here)
http://mydomain.com/ajax-container.php  (session variables are visible here)
http://mydomain.com/ajax-script.php     (session variables are visible here)
http://www.mydomain.com/ajax-script.php (session variables are NOT visible here)

Another one:

http://www.mydomain.com/login.php          (set session variables here)
http://www.mydomain.com/ajax-container.php (session variables are visible here)
http://www.mydomain.com/ajax-script.php    (session variables are visible here)
http://mydomain.com/ajax-script.php        (session variables are NOT visible here)
Salman A