ajax form redirect after submit

2019-08-12 12:49发布

问题:

Hello there i'm having problem with redirection after form has been submit. I'm using simple ajax form for displaying login errors in a div.

$(document).ready(function(){
$('#formlogin').on('submit', function (e) {

    $.ajax({
        type: 'POST', 
        url: 'login.php',
        data: $(this).serialize(),
        success: function(data) {
        $('div#ack').empty().append(data);

        } 

    });

    e.preventDefault();
});

The problem is after submit success it doesn't redirect to "logged_in.php"

Here is php login.

if (empty($username) === true || empty ($password) === true)    {
    $errors [] = 'Please enter both username and password!';

} else if (user_exists($username) === false)   {
    $errors [] = 'We can not find the name. Have you registered?';
} else {

    $login = login($username, $password);
    if ($login === false)  {
        $errors [] = 'This user name or password is incorrect.';

    } else {

        $_SESSION['user_id'] = $login;
        header('Location: logged_in.php');  
        exit();

    }


}

回答1:

If you redirect a page that was called with AJAX, it will not redirect the parent page.

What you should do is echo something that identifies that the user has successfully logged in.

Maybe instead of header('Location: logged_in.php'); you put:

echo "success";

Then, in your success function:

success: function(data) {
    if (data == "success")
        window.location = "logged_in.php";
    else
        alert("Wrong password.");
}

Note that success in ajax does not mean that you have successfully logged in, just means that the request to the page returned without error (500). You still need to decide what you want to do with your data.



回答2:

There are two different things here.

1 - Your AJAX function. It is on a page that call the server asynchronously

2 - Your login page. It is called by your page containing the AJAX

The code in your second page happens in the server, while your AJAX code is happening in your client.

You should return a success message in your php login page and then, in your success callback, check if the message is the correct one and that will mean the user logged in successfully. Once you check the message is the correct one, you can redirect the user from your success callback, doing: location.href = "yourUrl"