php session not working with ajax

痴心易碎 提交于 2020-12-13 11:07:30

问题


I've got a weird problem were php session variables are not working on pages accessed by ajax.

Server Side Code: s2.php

<?php
    session_start();
    header("Access-Control-Allow-Origin: *");

    echo '{"response":"'.$_SESSION["email"].'"}';

    exit();
?>

Client Side Code: index.php

$.ajax({
    url: 'mysite.com/s2.php',
    data: info,
    error: function() {
        console.log("broke :( ");
    },
    dataType: 'json',
    success: function(data) {
        console.log(data);
    },
    type: 'POST'
});

when I navigate to mysite.com/index.php i see: {response: ""} in the console.

When I navigate to mysite.com/s2.php I see {response: "email@address"} displayed in the browser.

I just don't understand why s2.php can access the session normally but not when run by an ajax call.

Also, when I run it on my home server, everything seems fine. But it's when it's run on my wife's bluehost.com server is when it has problems. Is this something with their settings?


回答1:


According with the official documentation, you must call the session_start() method in each one of pages where you are going to use the session, so try to call session_start() in your index.php.

This method starts new or resumes existing session, also check your PHPSESSID cookie sent with the AJAX request that match with your index.php PHPSESSID.



来源:https://stackoverflow.com/questions/48697597/php-session-not-working-with-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!