简体   繁体   中英

AJAX request through angular js POST to a PHP script returning whole html page not redirecting

JS

var app = angular.module('br', []);
app.controller('LoginCtrl', function($scope, $http) {
    $scope.valid = function() {
        var request = $http({
            method: "post",
            url: "php_files/login.php",
            data: {
                em: $scope.em,
                pw: $scope.pw
            },
        });

        request.success(function(data) {
            if (data == "invalid") {
                $scope.message = "Invalid email id or password!"
            }                
        });
    }
});

HTML

<body ng-controller="LoginCtrl">
    <form method="post">
        <table>
            <tr>
                <td>Email</td>
                <td><input type="email"  required="required" ng-model="em"/></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" required="required" ng-model="pw" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Login" ng-click="valid()"/></td>
            </tr>
            <tr>
                <td colspan="2" align='center' style="color: red">{{message}}</td>
            </tr>
        </table>
    </form>
</body>

PHP script

include './include_db.php';
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$em = $request->em;
$pw = $request->pw;
$query = "select em,pw from users where em='$em' and pw='$pw'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$got_em = $row["em"];
$got_pw = $row["pw"];
if ($em != $got_em && $pw != $got_pw) {
    echo "invalid";
} else {
    session_start();
    $_SESSION["em"] = $em;
    header("Location:home.html");
}

Now what I want is if the email id and password is wrong it should return invalid which is working but if they are correct it should redirect to home page which is not working.

in php_files/login.php:

if(!valid($username,$password)){
die("invalid");
} else {
die("https://logged_in_address");
}

in your javascript

                            request.success(function(data) {
                                if (data == "invalid") {
                                    $scope.message = "Invalid email id or password!"
                                } else {
                              window.location.replace(data);
/*redirect to the logged in page provided by login.php */
                               }
                            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM