2

I am writing a login function that should work through AJAX. If the user was able to login, there should be two new cookies. If it did not work (wrong email or password) the cookies are not being set.

My problem is this. I login, the cookies are set, but when it reaches the code where the cookie is checked, it is empty. When I reload my page, the cookie is there and everything works. Why is the cookie not available after the AJAX request?

Javascript:

$.ajax({  
    type: "POST",  
    url: "php/login.php",  
    data: dataString,  
    async: false
}); 

var email = '<?php echo $_COOKIE['email']; ?>';
var login = '<?php echo $_COOKIE['login']; ?>';

if(email != null && email != "" && login != null && login != "") {
    var html = '<h3>You are logged in as <b>' + email + '</b></h3><br><br><button id="logoutbtn" class="submitButton">Ausloggen</button>';
    $("#registInfos").empty();
    $(html).appendTo($('#registInfos'));
} else {
    console.log('login not successful');
    $('<p>Login failed, wrong email or password?</p>').appendTo($('#registInfos'));
}

Content of login.php:

<?php include('../../admin/php/connection.inc.php'); ?>
<?php header('Access-Control-Allow-Origin: *'); ?>

<?php
     if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        $email = $_POST['email'];
        $password = $_POST['password'];

        $abfrage = "SELECT email, password FROM ios_user WHERE email = '$email' LIMIT 1";
        $ergebnis = mysql_query($abfrage);
        $row = mysql_fetch_object($ergebnis);

        if($row->password == $password) {

            session_start();

            setcookie("login", "true", time()+3600*24*30*12, "/");
            setcookie("email", $email, time()+3600*24*30*12, "/");

            session_commit();
        } 
    }
?>
4

1 回答 1

1

问题是这段代码:

var email = '<?php echo $_COOKIE['email']; ?>';
var login = '<?php echo $_COOKIE['login']; ?>';

当页面加载时,服务器根据客户端发送的 cookie 呈现电子邮件、登录。但是当您发送 ajax 请求时,页面不会重新加载,这些值也不会改变。即使设置了 cookie,您仍然使用页面首次加载时呈现的旧值。

我建议你:

  • 登录后将用户重定向到另一个页面
  • 或者如果您想显示一条消息,您的服务器只是发回一条带有状态码的消息,指示成功登录,客户端的 javascript 可以解析该消息并显示成功信息(在这种情况下不需要依赖 cookie)
于 2013-06-02T04:01:19.153 回答