繁体   English   中英

使用ajax,php和mysql进行表单验证

[英]form validation with ajax, php, and mysql

我正在构建登录表单,并希望立即检查以确保电子邮件地址是我的数据库中的地址。

我环顾四周,尝试了一些不同的东西来使这项工作,但我似乎无法正常工作。

这是表格

<form>
<input type="text" id="email" name="email" placeholder="Email Address" onblur="checkEmail(this.value);" onchange="checkEmail(this.value);"/>
<input type="password" id="password" name="password" placeholder="Password"/>
<input type="button" id="login-signup" value="Login / Sign Up"/>
</form>

这是Javascript。 这是我认为问题所在。

function checkEmail(email) {
    // check to see if the email exists in the database using PHP and MySQL
    $.ajax({                                      
        url: 'login.php',               //the script to call to get data 
        type: 'post',  
        data: {
            email: $('#email').val()
        }, 
        dataType: 'json',               //data format      
        success: function(response) {       //on reception of reply
            if(response == 'match') {
                console.log('match');
            } else if (response == 'no match') {
                console.log('no match');
            } else if (response == 'error') {
                console.log('error');
            } else {
                console.log('who knows');
            }
        } 
    });

}

这里是login.php如果我导航到mywebsite.com/login.php?email=email,那么一切正常,所以我知道这正在做我需要的。 我想这个问题出在我的ajax中

$db_host = "host";
$db_user = "user";
$db_pass = "pass";
$db_name = "name";


$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name, $db_user, $db_pass);


if(isset($_GET['email'])) {
    $email = $_GET['email'];
    echo $email;
}

// Using prepared statements almost eliminates the possibility of SQL Injection.
$preparedQuery = $db->prepare("SELECT * FROM `members` WHERE `email` = :email");
$preparedQuery->bindValue(":email", $email);
$preparedQuery->execute();

// Retrieve the results from the database
$user = $preparedQuery->fetch(PDO::FETCH_ASSOC);

// If there is a user record print the user & pass... 
if($user != ''){
    echo 'match';
    $_SESSION['email'] = $email;
} else if ($user == '') {
    echo 'no match';
} else {
    echo 'error';
}

@ user4035建议从AJAX请求中删除数据类型,并获得返回结果的请求。 @Banik建议将$_GET更改$_GET $_POST ,这也有效。 现在整个事情都很完美

如果您尝试发送json对象,则需要读取原始数据。

$request_body = file_get_contents('php://input');
$email = json_decode($request_body, true);

然后,您将拥有一个数组中的电子邮件数据。 您还可以删除ajax调用中的数据类型,并读取$ _POST ['email']中的数据。 您正在发送帖子数据并尝试在$ _GET中访问它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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