Ajax和会话

时间:2014-05-24 16:26:58

标签: javascript php jquery ajax session

我有一个create_event.php页面。在填写事件详细信息后,用户可以登录。成功登录后,我希望用户在同一页面上阅读“Hello $ username,您现在已登录”(无需重新加载)。

对于登录过程,我使用以下 Ajax脚本

$.ajax({
                type : "POST",
                url : "system/process_login.php",
                data : query,
                cache : false,
                success : function(response) {
                    if (response === 'error') {
                        $('.feedback_message').text('Connection to database failed.');
                    };
                    if (response === 'failed') {
                        $('.feedback_message').text('Wrong login details.');
                    }
                    if (response === 'success') {
                        $('#step_login').text('Login successful!');
                    }
                }
            });

我想知道在ajax登录过程成功时如何初始化会话。在我的 process_login.php 中,我写了以下内容:

 session_start();

require_once 'db.php';

// Get values sent via ajax and prepare them for database
$username = $db -> real_escape_string($_REQUEST['username']);
$password = $db -> real_escape_string($_REQUEST['password']);

// Hash password
$password_hashed = sha1($password);


// Check if login information is correct
$query = "SELECT * FROM users WHERE username='$username' AND password='$password_hashed'";
$results = $db -> query($query);
if ($db -> error) {
    $response = 'error';
    echo $response;
}
if (mysqli_num_rows($results) > 0) {
    $_SESSION['username'] = $username;
    $response = 'success';
    echo $response;
} else {
    $response = 'failed';
    echo $response;
}

?>

我的问题:当ajax登录过程成功时,$ _SESSION ['username']变量是否可用?如何检索? 在同一页面的顶角,即我的create_event.php,我希望用户阅读“Hello $ username,您现在已登录!”..

1 个答案:

答案 0 :(得分:0)

以上评论(未经测试)

PHP

if (mysqli_num_rows($results) > 0) {
    $user = $_SESSION['username']; // or, other method(s) of deriving accurate `username` / `user`
    $response = $user;
    echo $response;
}

JS

success : function(response) {
                    if (response === 'error') {
                        $('.feedback_message').text('Connection to database failed.');
                    };
                    if (response === 'failed') {
                        $('.feedback_message').text('Wrong login details.');
                    }
                    if (response != "error" && response != "failed") {
                        $('#step_login').text("Hello" + response + ", you are logged-in now!");
                    }
                }