Код работает. Я добавила валидацию, ответ от сервера, переделала часть кода и столкнулась с тем, что не могу получить результат на страницу с капчей. Другими словами, если введённые данные не прошли валидацию на стороне сервера, то форма не отправляется и ни как об этом не сообщает пользователю, если валидация на php пройдена, то всё работает и отправляет мне на почту письмо.
$(document).ready(function() {
var contactForm = $("#contactForm");
//We set our own custom submit function
contactForm.on("submit", function(e) {
//Prevent the default behavior of a form
e.preventDefault();
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact_form input[required=true], #contact_form textarea[required=true]").each(function(){
$(this).css('border-color','');
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if(proceed){ //everything looks good! proceed...
post_data = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'phone' : $('input[name=phone]').val(),
'message' : $('textarea[name=message]').val(),
'captcha' : grecaptcha.getResponse()
};
//Ajax post data to server
$.post('mail.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
$("#contact_form #contact_body").slideUp(); //hide form after success
}
$("#contact_form #contact_results").hide().html(output).slideDown();
}, 'json');
}else{
alert("validation error");
}
});
});
<?php
$name=filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$email=filter_var($_POST["email"], FILTER_SANITIZE_STRING);
$phone=filter_var($_POST["phone"], FILTER_SANITIZE_STRING);
$message=filter_var($_POST["message"], FILTER_SANITIZE_STRING);
$secret="";
$response=$_POST["captcha"];
$verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
$captcha_success=json_decode($verify);
if ($captcha_success->success==true) {
//additional php validation
if(strlen($name)<2){ // If length is less than 2 it will output JSON error.
$output = json_encode(array('type'=>'error', 'text' => 'Неправильно введено им\'я!'));
die($output);
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ //email validation
$output = json_encode(array('type'=>'error', 'text' => 'Неправильно введено email!'));
die($output);
}
if(!filter_var($phone, FILTER_SANITIZE_NUMBER_FLOAT)){ //check for valid numbers in phone number field
$output = json_encode(array('type'=>'error', 'text' => 'Неправильно введен номер телефона.'));
die($output);
}
if(strlen($message)<3){ //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'Введитіть Ваше повідомлення. Мінимальна довжина повідомлення - 4 символа.'));
die($output);
}
//This user was not verified by recaptcha.
$to_email = "example@gmail.com"; //Recipient email, Replace with own email here
$subject = "order";
$message_body = $message."\r\n\r\n From : ".$name."\r\nEmail : ".$email." \r\nPhone :".$phone;
//proceed with PHP email.
$headers = 'From: '.$name.'' . "\r\n" .
'Reply-To: '.$email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail = mail($to_email, $subject, $message_body, $headers);
if(!$send_mail){
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Вітаємо, '.$name .'. Ваше повідомлення відправлено. Мы зв\'яжемося з Вами у найближчий час.'));
die($output);
}
}else if ($captcha_success->success==false) {
//This user is verified by recaptcha
echo "robots = false";
}
Форма.
<form id="contactForm">
<div id="contact_results"></div>
<input type="text" name="name" placeholder="Your name..." required="true"/>
<br>
<input type="text" name="email" placeholder="Your email..." required="true"/>
<br>
<input type="text" name="phone" placeholder="0978888888"/>
<br>
<textarea name="message" placeholder="Your message..." required="true"></textarea>
<br>
<div class="g-recaptcha" data-sitekey="mykey"></div>
<br>
<input type="submit" />
</form>