简体   繁体   中英

How to implement reCAPTCHA with AJAX for sending mail in php?

I'm trying to add Google's recaptcha in my website's contact form. I've used the <input type="submit"> instead of button tag for submitting the form. But it doesn't work with AJAX. And with button tag, the captcha response is always empty. You can check the problem on vipiny.com .

This is the contact form.

<form action="" method="post" id="contactForm" name="contactForm">
    <div>
        <label for="contactName">Name <span class="required">*</span></label>
        <input type="text" value="" size="35" id="contactName" name="contactName">
    </div>
    <div>
        <label for="contactEmail">Email <span class="required">*</span></label>
        <input type="text" value="" size="35" id="contactEmail" name="contactEmail">
    </div>
    <div>
        <label for="contactSubject">Subject</label>
        <input type="text" value="" size="35" id="contactSubject" name="contactSubject">
    </div>
    <div>
        <label for="contactMessage">Message <span class="required">*</span></label>
        <textarea cols="50" rows="3" id="contactMessage" name="contactMessage"></textarea>
    </div>
    <div class="g-recaptcha captcha" data-theme="light" data-sitekey="6LfAkhQUAAAAAC2D3LxhB9XtYeoJGhuvR31sq9HW"></div>
    <div>
        <button class="submit">Submit</button>
    </div>
</form> <!-- Form End -->

And I'm using ajax to send the data to sendMail.php file.

$('form#contactForm button.submit').click(function() {

  $('#image-loader').fadeIn();

  var contactName = $('#contactForm #contactName').val();
  var contactEmail = $('#contactForm #contactEmail').val();
  var contactSubject = $('#contactForm #contactSubject').val();
  var contactMessage = $('#contactForm #contactMessage').val();

  var data = 'contactName=' + contactName + '&contactEmail=' + contactEmail +
           '&contactSubject=' + contactSubject + '&contactMessage=' + contactMessage;

  $.ajax({

      type: "POST",
      url: "inc/sendEmail.php",
      data: data,
      success: function(msg) {

        // Message was sent
        if (msg == 'OK') {
           $('#image-loader').fadeOut();
           $('#message-warning').hide();
           $('#contactForm').fadeOut();
           $('#message-success').fadeIn();   
        }
        // There was an error
        else {
           $('#image-loader').fadeOut();
           $('#message-warning').html(msg);
            $('#message-warning').fadeIn();
        }

      }

  });
  return false;   }); });

And this is so far my sendMail.php file. I'm trying to validate that if $error['captcha'] is empty along with other input field checks, the mail will be sent.

$secret = "<--secret key-->";
$user_ip = $_SERVER['REMOTE_ADDR'];

if(isset($_POST['g-recaptcha-response'])){
    $response = $_POST['g-recaptcha-response'];
    // echo "GOT response:".$response."<br/>";
}
else{
    // echo "No reCAPTCHA response.<br/>";
}

//Verify response data
$verifyResponse = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$user_ip");
$responseData = json_decode($verifyResponse);
if(!$responseData->success){
    $error['captcha'] = "Please prove that you're not a robot.";    
}

Any suggestions what might be going wrong?

You forgot to add the ? after the url

url: "inc/sendEmail.php?",

OR

you could leave out the ? and send your data like

data: { this: this, that: that, another: another},

also since you are not posting the g-recaptcha-response to the php file with the form, but instead with AJAX you have to send the post manually to your php file.

var g-recaptcha-response= $('#contactForm .g-recaptcha-response').val();

var data = 'contactName=' + contactName + '&contactEmail=' + contactEmail +
       '&contactSubject=' + contactSubject + '&contactMessage=' + contactMessage + '&g-recaptcha-response=' + g-recaptcha-response;

you made also need this to confirm the recaptcha in php

  require_once('recaptchalib.php');
  $privatekey = "your_private_key";
  $resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

  if (!$resp->is_valid) {
    // What happens when the CAPTCHA was entered incorrectly
    die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
         "(reCAPTCHA said: " . $resp->error . ")");
  } else {
    // Your code here to handle a successful verification
  }

https://developers.google.com/recaptcha/old/docs/php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM