我有一个非常简单的表单,用于获取电子邮件地址以发送简报。我试图找出如何添加一些服务器端验证来检查输入的电子邮件地址是否已经在我的database
中。然后,如果已经输入,它不允许表单提交,并抛出用户可以看到的错误。
我如何检查并显示错误?
<form action="" method="POST" id="newsletter-form">
<input type="email" id="footer-grid1-newsletter-input" placeholder="Your Email Address" pattern=".{3,}" required>
<input type="submit" id="footer-grid1-newsletter-submit" name="submit" value=' '>
</form>
$("#newsletter-form").on("submit", function (event) {
event.preventDefault();
var newsletter_email = $("#footer-grid1-newsletter-input").val();
var targeted_popup_class = jQuery(this).attr('data-popup-open');
$.ajax({
url: "newsletterSend.php",
type: "POST",
data: {
"newsletter_email": newsletter_email
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to insert email!");
alert(data);
} else {
$("#newsletter-form")[0].reset();
$('.newsletter-popup').fadeIn(350).delay(2000).fadeOut();
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
$newsletter_email = $_POST['newsletter_email'];
try {
$con = mysqli_connect("localhost", "", "", "");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("INSERT INTO newsletter (email, subscribed) VALUES (?, NOW())");
if ( false===$stmt ) {
die('Newsletter email prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt->bind_param('s', $newsletter_email);
if ( false===$stmt ) {
die('Newsletter email bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->execute();
if ( false===$stmt ) {
die('Newsletter email execute() failed: ' . htmlspecialchars($stmt->error));
}
答案 0 :(得分:0)
以下内容可以帮助您。
JS:
$(document).ready(function(){ //newly added
$('#footer-grid1-newsletter-submit').click(function() {
var emailVal = $('#footer-grid1-newsletter-input').val(); // assuming this is a input text field
$.post('checkemail.php', {'email' : emailVal}, function(data) {
if(data=='exist'){
$('#alert').html("<p> You are already subscribed to our website</p>");
return false;
}
else {
$('#newsletter-form').submit();
}
});
});
});
HTML:
<form action="" method="POST" id="newsletter-form">
<input type="email" id="footer-grid1-newsletter-input" placeholder="Your Email Address" pattern=".{3,}" required>
<input type="submit" id="footer-grid1-newsletter-submit" name="submit" value=' '>
</form>
PHP:
$con = mysqli_connect("localhost", "", "", "");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT email FROM newsletter WHERE email = '" .$_POST['email'] ."'";
$select = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows > 0) {
echo "exist";
}
else {
$stmt = $con->prepare("INSERT INTO newsletter (email, subscribed) VALUES (?, NOW())");
}