简体   繁体   中英

Can't retrieve session variable from PHP script

I have an ajax posting of a form so that I can return values from PHP exactly as it shows here: https://jonsuh.com/blog/jquery-ajax-call-to-php-script-with-json-return/ . There's a slight difference though, my response.php script is like this:

<?php
session_start();

$email = $_SESSION['email'];

?>

<?php    
if (is_ajax()) {
    if (isset($_POST["action"]) && !empty($_POST["action"])) { 
        $action = $_POST["action"];
        switch($action) { 
        case "test": test_function(); break;
        }
    }
}

function is_ajax() {
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&   strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

function test_function(){
    $return = $_POST;
    $x = $return["Profile"];

    define('DB_NAME', 'STUDENTS');
    define('DB_USER', 'STUDENTS');
    define('DB_PASSWORD', 'PASSWORD');
    define('DB_HOST','HOST');

    $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);       
    $db_selected = mysql_select_db(DB_NAME, $link); 

    $sql = "UPDATE  `STUDENTS`.`Students` SET  `Fbprofile` =  '$x' WHERE  `Students`.`StudEmail` = '$email'  ";

    $return["json"] = json_encode($return);
    echo json_encode($return);
}
?>

As you can see, the only difference is that I'm updating an SQL database. The problem is that I want to update the Fbprofile column where StudEmail equals the email session variable. This session variable works perfectly in all other pages, but I can't seem to retrieve it in my response.php. What actually happens is that the SQL update works but only updates all rows that have no email value in them, so I'm guessing it's not reading the $email variable. Thank you very much for your help.

It's a variable scope problem. You set $email outside of test_function , so it's not visible inside the function. If you had error reporting enabled, you would have seen a notice about the undefined variable.

You should pass it as an argument to the function:

    case "test": test_function($email); break;

...

function test_function($email) {
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM