使用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=电子邮件然后一切正常,所以我知道这是在做我需要做的事情。我想问题出在我的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建议将CCD_ 2改为CCD_。现在整个事情都很完美
如果您试图发送json对象,则需要读取原始数据。
$request_body = file_get_contents('php://input');
$email = json_decode($request_body, true);
然后,您将获得一个数组中的电子邮件数据。您还可以删除ajax调用中的数据类型,并读取$_POST['email']中的数据。您正在发送邮件数据,并试图在$_GET 中访问它
相关文章:
- 解析javascript表单验证器
- Jquery表单验证插件-如果选中复选框,如何在提交时执行某些操作
- 自定义表单验证和提交
- Javascript表单验证的缺点
- Jquery的表单验证不起作用
- 语义ui表单验证:图像url
- jQuery表单验证适用于Mozilla和Internet Explorer,但不适用于Chrome或Safari
- JavaScript表单验证-“;“错误”;不按需要工作
- Mailchimp内联表单验证不适用于JS加载的HTML
- jQuery/JS获胜't在表单验证后重定向
- jquery表单验证复选框错误显示
- javascript表单验证-数值和密码
- 我想知道如何在javascript中进行表单验证
- jQuery表单验证(如果==“执行此操作”)仅适用于第一次输入
- 使用记录保存的消息进行表单验证
- 表单验证工作不正常,在不检查条目的情况下继续
- 如何对未知表单元素进行表单验证
- 使用ajax、php和mysql进行表单验证
- JS表单验证未发生
- 表单验证jsphp路径