John Davidson

javascript - Google Recaptcha with PHP mailer not working

0 comments
Message:


So I am trying to use the recaptcha v2 where I have completed the client side part of putting the captcha but the another of server side validation gives an error where the form is submitted but the message shows that "Please click on the reCAPTCHA box." whereas the button is been clicked & also the mail part is not working. I know there is some issue with the JS code to take the POST value of recaptcha in PHP page but could not work on it.. Can anyone help me with it? I have Attached the HTML, JS & PHP code below....


HTML


<form class="comment-one__form contact-form-validated" novalidate="novalidate">
<div id="success" class="alert alert-success"></div>
<div class="row">
<div class="col-xl-6">
<div class="comment-form__input-box">
<input type="text" placeholder="Your name" name="name" id="name">
</div>
</div>
<div class="col-xl-6">
<div class="comment-form__input-box">
<input type="email" placeholder="Email address" name="email" id="email">
</div>
</div>
<div class="col-xl-6">
<div class="comment-form__input-box">
<input type="text" placeholder="Phone number" name="phone" id="phone">
</div>
</div>
<div class="col-xl-6">
<div class="comment-form__input-box">
<input type="text" placeholder="Subject" name="subject" id="subject">
</div>
</div>
</div>
<div class="row">
<div class="col-xl-12">
<div class="comment-form__input-box text-message-box">
<textarea name="message" id="message" placeholder="Write comment"></textarea>
</div>
<div class="comment-form__btn-box">
<div class="g-recaptcha" id="gcaptcha" data-sitekey="SITE KEY"></div>
<button type="submit" id="csubmit" class="thm-btn comment-form__btn">Send a
message</button>
</div>
</div>
</div>
</form>

JS


if ($(".contact-form-validated").length) {
$(".contact-form-validated").validate({
// initialize the plugin
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
phone: {
required: true,
digits: true,
minlength: 10,
maxlength: 10,
},
message: {
required: true
},
subject: {
required: true
}
},
messages: {
name: {
required: "Please enter your name",
},
email: {
required: "Please enter your email",
email: "Please enter vaild email",
},
phone: {
required: "Please enter your number",
digits: "Please enter only numbers",
minlength: "The phone number cannot be less than 10 digits",
maxlength: "The phone number cannot be more than 10 digits",
},
message: {
required: "Please enter your message",
},
},
submitHandler: function (form) {
// sending value with ajax request
$('#csubmit').html('Sending...');
var user_name = $("#name").val();
var user_email = $("#email").val();
var user_phone = $("#phone").val();
var user_subject = $("#subject").val();
var user_message = $("#message").val();
var gcaptcha = $(".g-recaptcha").val();

var formDatanew = new FormData();
formDatanew.append("name", user_name);
formDatanew.append("email", user_email);
formDatanew.append("phone", user_phone);
formDatanew.append("subject", user_subject);
formDatanew.append("message", user_message);
formDatanew.append("g-recaptcha-response", gcaptcha);
$.ajax({
url: 'vendor/process.php',
type: "POST",
data: formDatanew,
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false,
success: function (data) {
$("form").trigger("reset");
$('#csubmit').html('Send Message');
$('#success').fadeIn().html(data);
setTimeout(function(){
$('#success').fadeOut("Slow");
}, 5000);
}
});
return false;
}
});
}

PHP


<?php 


use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../PHPMailer/src/Exception.php';
require '../PHPMailer/src/PHPMailer.php';
require '../PHPMailer/src/SMTP.php';

if(isset($_POST['name']))
{
$name = addslashes($_POST['name']);
$email= addslashes($_POST['email']);
$contact = addslashes($_POST['phone']);
$subject = addslashes($_POST['subject']);
$message = addslashes($_POST['message']);

if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){

// Your Google reCAPTCHA generated Secret Key here
$secret = 'SECRET KEY';

$serverError = '';

if( ini_get('allow_url_fopen') ) {
//reCAPTCHA - Using file_get_contents()
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
} else if( function_exists('curl_version') ) {
// reCAPTCHA - Using CURL
$fields = array(
'secret' => $secret,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
);

$verifyResponse = curl_init("https://www.google.com/recaptcha/api/siteverify");
curl_setopt($verifyResponse, CURLOPT_RETURNTRANSFER, true);
curl_setopt($verifyResponse, CURLOPT_TIMEOUT, 15);
curl_setopt($verifyResponse, CURLOPT_POSTFIELDS, http_build_query($fields));
$responseData = json_decode(curl_exec($verifyResponse));
curl_close($verifyResponse);
} else {
$arrResult = array ('response'=>'error','errorMessage'=>'You need CURL or file_get_contents() activated in your server. Please contact your host to activate.');
$serverError = true;
}

if(empty($serverError)) {

if($responseData->success) {

$mail = new PHPMailer;
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->Mailer = "smtp";
$mail->Host = "smtp.gmail.com"; /*SMTP server*/
$mail->SMTPAuth = true;
$mail->SMTPSecure = "ssl";
$mail->Port = 465;
$mail->Username = "*****"; /*Username*/
$mail->Password = "*****"; /**Password**/
$mail->isHTML(true);
$mail->FromName = $name;
$mail->addReplyTo($email, $name);
$mail->Body = $body;
$mail->From = $email;
$mail->Subject = "Contact Form";
$mail->AddAddress("[email protected]");

if($mail->Send()){

echo "Thank you! We will get back to you soon.";
}
else{
echo "Oops! Something went wrong.";
}

} else {
echo "Robot verification failed, please try again";
}
}

} else {
echo "Please click on the reCAPTCHA box.";
}

}

?>


My Answer:
There are a few issues in your code that need to be addressed:

1. In your JS code, you are trying to get the value of the reCAPTCHA response using `$(".g-recaptcha").val();`. This is incorrect as the reCAPTCHA response is not a value of an input field. You should use `grecaptcha.getResponse()` to get the reCAPTCHA response.

2. In your PHP code, you are trying to use `$body` in the mail function, but it is not defined anywhere in your code. You should define the body of the email before using it in the mail function.

3. Make sure that the PHPMailer library is correctly included in your PHP file and the file paths are correct.

Here is the updated JS code to get the reCAPTCHA response:

javascript
var gcaptcha = grecaptcha.getResponse();


And here is an example of how you can define the body of the email in your PHP code:

php
$body = "Name: $name\n";
$body .= "Email: $email\n";
$body .= "Phone: $contact\n";
$body .= "Subject: $subject\n";
$body .= "Message: $message\n";


Make sure to make these changes and test your code again. If you still face issues, please let me know.

Rate this post

5 of 5 based on 8388 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us