我的目标是在发送之前要求选中复选框。如果复选框为空,则访问者应收到一条消息。我尝试使用isset和empty(),但是对我来说不起作用。我的错误在哪里?有什么想法吗?
HTML
<form id="contact-form" name="contact-form" action="mail.php" method="POST" onsubmit="return validateForm()">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="form" name="form" value="1" checked>
<label for="form" class="custom-control-label underline"></label>
</div>
<div class="text-center text-md-left pl-4">
<a class="btn btn-send" onclick="validateForm()">Send</a>
</div>
<div id="status"></div>
</form>
JS
function validateForm() {
document.getElementById('status').innerHTML = "Sending...";
formData = {
'name' : $('input[name=name]').val(),'email' : $('input[name=email]').val(),'subject' : $('input[name=subject]').val(),'message' : $('textarea[name=message]').val(),'form' : $('input:checkbox[name=form]').is(':checked')
};
$.ajax({
url : "mail.php",type: "POST",data : formData,success: function(data,textStatus,jqXHR)
{
$('#status').text(data.message);
if (data.code) //If mail was sent successfully,reset the form.
$('#contact-form').closest('form').find("input[type=text],textarea").val("");
},error: function (jqXHR,errorThrown)
{
$('#status').text(jqXHR);
}
});
}
mail.php
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
$form = $_POST['form'];
header('Content-Type: application/json');
if($form !== '1'){
print json_encode(array('message' => 'Checkbox must be checked','code' => 0));
exit();
}
if ($name === ''){
print json_encode(array('message' => 'Name cannot be empty','code' => 0));
exit();
}
if ($email === ''){
print json_encode(array('message' => 'Email cannot be empty','code' => 0));
exit();
} else {
if (!filter_var($email,FILTER_VALIDATE_EMAIL)){
print json_encode(array('message' => 'Email format invalid.','code' => 0));
exit();
}
}
if ($subject === ''){
print json_encode(array('message' => 'Subject cannot be empty','code' => 0));
exit();
}
if ($message === ''){
print json_encode(array('message' => 'Message cannot be empty','code' => 0));
exit();
}
$content="From: $name \nEmail: $email \nmessage: $message";
$recipient = "mymail@gmail.com";
$mailheader = "From: $email \r\n";
mail($recipient,$subject,$content,$mailheader) or die("Error!");
print json_encode(array('message' => 'Email successfully sent!','code' => 1));
exit();
?>