Brained Washed
Brained Washed

Reputation: 703

How can I direct to another page using jquery ajax given the situation below?

I have a php script that validate users by their email and password, if it is invalid my script echoes something like "Unable to login" and if it is success it will direct to another page, How can I do that?

Here's my php code:

if(isset($_POST['email'])&&isset($_POST['password'])){
    $email = $_POST['email'];
    $password = $_POST['password'];

    $result = userAuthentication($email,$password);

    if($result == false){
        echo 'Unable to login';
    }
    else if($result == true){
        header("location: success.php");
    }
}

Here's my js code:

$(function() {
    $("button").button();
    $("#clickme").click(function(){
        $.post("check.php", {
            "email": $("#txtEmail").val(),
            "password": $("#txtPassword").val()
        },
        function(msg){
            $(".message").html(msg);
        });
        return false;
    });
});

Upvotes: 1

Views: 275

Answers (1)

Mihai Iorga
Mihai Iorga

Reputation: 39704

You cannot redirect from PHP like that. You can return success message and redirect from javascript:

php:

if(isset($_POST['email'])&&isset($_POST['password'])){
    $email = $_POST['email'];
    $password = $_POST['password'];

    $result = userAuthentication($email,$password);

    if($result == false){
        echo 'Unable to login';
    }
    else if($result == true){
        echo 'success';
    }
}

javascript:

$(function() {
    $("button").button();
    $("#clickme").click(function(){
        $.post("check.php", {
            "email": $("#txtEmail").val(),
            "password": $("#txtPassword").val()
        },
        function(msg){
            $(".message").html(msg);
            if(msg == 'success'){
                window.location = 'success.php';
            }
        });
        return false;
    });
});

Upvotes: 2

Related Questions