noe*_*293 5 javascript php ajax jquery
我有一个简单的表单,用于向数据库提交电子邮件地址。我想先使用javascript和AJAX检查该表中是否已存在该电子邮件地址。无论行是否已存在于数据库中,我使用的代码始终返回true。有什么提示吗?
JS代码
<script>
$('form').submit(function(e)
{
alert('submit intercepted');
e.preventDefault(e);
var u = $('#email').val();
$.ajax({
url: './test2.php',
type: 'POST',
data: u,
success: function (response) {
//get response from your php page (what you echo or print)
$('#status').append('<p>The email is ok to use and the row has been inserted </p><p>' + response);
console.log('Submitted');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
alert('Email exists');
}
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
HTML代码
<form id="form" action="./test2.php" method="post">
E-mail: <input type="email" name="email" id="email" required><br>
<span id="status"> </span>
<input type="submit" id="btnsub">
</form>
Run Code Online (Sandbox Code Playgroud)
PHP代码
if(isset($email)) {
$sql_email_check = $conn->query("SELECT Email FROM test WHERE Email='$email' LIMIT 1") ;
$email_check = $sql_email_check->num_rows;
if ($email_check < 1) {
//return "Available";
return true;
//header('Location: /test.php');
exit();
}
else
{
//return "Unavailable";
return false;
//header('Location: /test.php');
exit();
}
}
Run Code Online (Sandbox Code Playgroud)
所以基本上问题是将答案从 php 代码返回到 ajax 函数。由于某种原因,返回值没有按照预期正确解释(无论如何,根据我的理解)
PHP代码
if(isset($email)) {
$sql_email_check = $conn->query("SELECT Email FROM test WHERE Email='$email' LIMIT 1") ;
$email_check = $sql_email_check->num_rows;
if ($email_check == 0) {
echo 'true';
return;
}
else
{
echo 'false';
return;
}
}
Run Code Online (Sandbox Code Playgroud)
JS代码
<script>
$('form').submit(function(e)
{
alert('submit intercepted');
e.preventDefault(e);
var u = { 'email': $('#email').val() };
$.ajax({
url: 'test2.php',
type: 'POST',
//dataType: 'string',
data: u,
success: function (response) {
//get response from your php page (what you echo or print)
console.log(response);
if (response === 'true') {
$('#status').append('<p>The email is ok to use and the row has been inserted </p><p>' + response);
} else {
console.log('Email does exist ');
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
</script>
Run Code Online (Sandbox Code Playgroud)