nimrod
nimrod

Reputation: 5732

Cookie not availabe after setting it in AJAX request

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();
        } 
    }
?>

Upvotes: 2

Views: 1089

Answers (1)

Khanh TO
Khanh TO

Reputation: 48972

The problem is this code:

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

When the page loads, the server renders email, login based on the cookies sent by client. But when you send an ajax request, the page is not reloaded and these values don't change. Even if the cookies are set, you are still using the old values rendered when page first loads.

I suggest you either:

  • redirect the user to another page after login
  • or in case you want to display a message, your server just sends back a message with status code indicating success login, the javascript on client side can parse that message and display success information (don't need to rely on cookies in this case)

Upvotes: 1

Related Questions