Hack Forums
[PHP] AJAX - Php session variables are null on other php files. - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Web Development (https://hackforums.net/forumdisplay.php?fid=183)
+---- Thread: [PHP] AJAX - Php session variables are null on other php files. (/showthread.php?tid=6074158)



AJAX - Php session variables are null on other php files. - Aussie - May 3, 2020

Duly note, I am using session_start(); preceding any code in both these php files:

Problem in a minimum reduced format:

index.php
PHP Code

<?php
  session_start
();
  
$_SESSION['msg'] = 'hello';
?>

Inside index.php, posting to add_to_cart.php using AJAX.
PHP Code

<?php 
$.ajax({
                
type:"POST",
                
url:"add_to_cart.php",
                
async: false, //tested with this true and now false
                
data:{test_product:productName},
                
success:function(response){
                  
alert(response);
                }
              }); 

add_to_cart.php:

PHP Code

<?php
    session_start
();

    echo 
json_encode($_SESSION['msg']);
?>
The output of the alert is null


RE: AJAX - Php session variables are null on other php files. - Charger - May 3, 2020

in add_to_cart.php do this and see what happens.
PHP Code

<?php
    session_start
();
    
print_r($_SESSION);
    echo 
json_encode($_SESSION['msg']);
?>



RE: AJAX - Php session variables are null on other php files. - Aussie - May 3, 2020

Hi,

I have done a var_dump on two servers. My home nginx, and my apache.

The vardump reveals session is intact in apache, however null on nginx. I will tweak the settings accordingly. There seems to be no issue with the code.

Thanks to the above answers.

Thread closed.