通过PHP中的AJAX接收多个数据?

时间:2016-09-21 07:48:25

标签: php jquery ajax post

我正在使用登录表单,用户在他的电子邮件中输入,通过AJAX验证,之后通过AJAX验证密码。 这是代码, JS代码 -

//AJAX for email input field
function emailCheck(email) {
    return $.ajax({
        type: "POST",
        url: "ajax_index.php",
        data: "email=" + email
    });
}

//AJAX for password input field
function passwordCheck(password, email) {
    return $.ajax({
        type: "POST",
        url: "ajax_index.php",
        data: {password: password, email: email}
    });
}

PHP代码 -

//receives POST request from email field
if (isset($_POST['email'])) {
    $email = mysqli_real_escape_string($dbconn, $_POST['email']);

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo -1;
    } else {
        $query = "SELECT * from users WHERE email = '$email'";
        $query_result = mysqli_query($dbconn, $query) or die(mysqli_error($dbconn));
        $result_rows = mysqli_num_rows($query_result);

        echo $result_rows;
    }
}

//receives POST from password field
if (isset($_POST['password'], $_POST['email'])) {
    $email = mysqli_real_escape_string($dbconn, $_POST['email']);
    $password = mysqli_real_escape_string($dbconn, $_POST['password']);

    $query = "SELECT email, password from users WHERE email = '$email'";
    $query_result = mysqli_query($dbconn, $query) or die(mysqli_error($dbconn));
    $result_rows = mysqli_num_rows($query_result);

    $row = mysqli_fetch_assoc($query_result);

    if (password_verify($password, $row['password'])) {
        echo 1;
    }
    else {
        echo 0;
    }
}

如您所见,对于密码字段,我必须同时获取$_POST['password']$_POST['email'],以便我可以针对该电子邮件验证密码。但这会调用两个处理程序,一个只用于电子邮件字段,另一个用于电子邮件和密码,我只想运行它。那么,我怎么能解决这个问题呢? 谢谢。

1 个答案:

答案 0 :(得分:0)

所以,愚蠢的问题,我只需要将密码字段的处理程序放在条件块中的电子邮件字段的处理程序中。所以如果我改变这个就行了 -

if (isset($_POST['email'])) {
    if(isset($_POST['password'])) {
        $email = mysqli_real_escape_string($dbconn, $_POST['email']);
        $password = mysqli_real_escape_string($dbconn, $_POST['password']);

        $query = "SELECT email, password from users WHERE email = '$email'";
        $query_result = mysqli_query($dbconn, $query) or die(mysqli_error($dbconn));
        $result_rows = mysqli_num_rows($query_result);

        $row = mysqli_fetch_assoc($query_result);

        if (password_verify($password, $row['password'])) {
            echo 1;
        }
        else {
            echo 0;
        }
    }
    else {
        $email = mysqli_real_escape_string($dbconn, $_POST['email']);

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            echo -1;
        } else {
            $query = "SELECT * from users WHERE email = '$email'";
            $query_result = mysqli_query($dbconn, $query) or die(mysqli_error($dbconn));
            $result_rows = mysqli_num_rows($query_result);

            echo $result_rows;
        }
    }
}

或者如Sasikumar所述,使用额外的变量也可以。