Why can't I access session variables from my AJAX-called PHP script?

前端 未结 7 1974
情话喂你
情话喂你 2021-01-11 11:03

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

相关标签:
7条回答
  • 2021-01-11 11:26

    I also caught myself on having one little, tiny, hard to see, space just before "< ? php " This ended up sending information back and disallowing the session to start because header information was already sent. May not be the case for anyone else, but it tripped me up and brought me to this page in search of an answer.

    0 讨论(0)
  • 2021-01-11 11:27

    Make sure no content has been echoed (not even a whitespace) before calling session_start().
    To be safe, put the code as the first code of whatever template you used for the page. The function will not work if content has been sent to the browser.
    To test and see where the problem is, call the page as a stand-alone, instead of through AJAX and ensure that it works before AJAXing it.

    0 讨论(0)
  • 2021-01-11 11:33

    My own error was BOM character in my ajax file.I was need to use session variable in a ajax called php file.I tried to start session by session_start() but "cannot modify header information" occurs.I removed BOM character and code works very well.

    0 讨论(0)
  • 2021-01-11 11:37

    In jQuery or JavaScript, you can get the session value like this:

    var StepIndexval = '<%= Session["StepIndex"].ToString() %>';
    
    alert(StepIndexval);
    
    0 讨论(0)
  • 2021-01-11 11:40

    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.

    0 讨论(0)
  • 2021-01-11 11:40

    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)
    
    0 讨论(0)
提交回复
热议问题