Need to return recaptcha response while using AJAX, jQuery .submit on button, and keep serialized data intact

StackOverflow https://stackoverflow.com/questions/7226765

Pregunta

I've looked everywhere and have tried 10 different similar issues but neither works exactly how I need it to.

I have a simple form with validation using validationEngine (and this works fine, it validates the required fields and the captcha field and won't allow the jQuery .submit() function to process until they are valid). This code is supposed to collect the recaptcha fields, send them via AJAX post to the php handler, and receive a response, all the while using .submit() for non-invasive code:

Javascript:

function validateCaptcha() {
   challengeField = $("input#recaptcha_challenge_field").val();
   responseField = $("input#recaptcha_response_field").val();
   var html = $.ajax({
   type: "POST",
   url: form.attr('action'),
   data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
   async: false
   }).responseText;

   if(html != "Valid") {
     $("#captchaError").html('<p class="error">The security code you entered did not match. Please try again.</p>');
     $captchaFlag = "Invalid";
     Recaptcha.reload();
   } else {
     $("#memberInformation span").css({'color':'green'});
     $("#memberInformation span").html(html.message).show(3000);
     $("#captchaError").html('<p>Success!</p>');
     $captchaFlag = "Valid";
     dataString = form.serializeArray();
     getSearchMembers(dataString);
   }
}


   formID.submit(function() {
     var form = $(this);
     if (formID.validationEngine('validate')) { //if it validates
       $('#memberInformation span').html('');
       //Captcha check
     } //end if (formID.validationEngine('validate'))
     else { //if does not validate
       $('#memberInformation span').css('color','#ff0000').html('Please fill out required fields').show(3000);
     } //end else
     return false;
    }); //end formID.submit

PHP

$privatekey = "1234567890"; //<!----- private key here
$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
echo "Error";
die ("The reCAPTCHA wasn't entered correctly. Please go back and try it again. (reCAPTCHA said: " . $resp->error . ")");
} else {
echo "Valid";
}
?>

Everything works except the sending of the _post data to the php file, so it always responds as "invalid". Any ideas. I want to use .submit(), and AJAX, and the current validator. Otherwise anything else can change all it needs to.

¿Fue útil?

Solución

First, dump your post data at the server side to see if all values are set. Also, verify in your browser what is actually sent by your ajax request. In Chrome you can check this from the developers panel at tab 'Network'. See if your post is correct. Also, review whether you have put the correct keys in the correct location, I once put the public key at the private variable and vice versa.

Otros consejos

You can use this:

index.php(the page where your CAPTCHA appears)

<html>
    <body> <!-- the body tag is required or the CAPTCHA may not show on some browsers -->
      <!-- your HTML content -->
<script type="text/javascript">
function showHint()
{
var xmlhttp;
var x=document.form.recaptcha_challenge_field.value;
var y=document.form.recaptcha_response_field.value;
if (x.length==0)
  {
  document.getElementById("hint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("hint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","gethint.php?q="+x+"&r="+y,true);
xmlhttp.send();
}
</script>
 <script type="text/javascript">
 var RecaptchaOptions = {
    theme : 'white'
 };
 </script>
      <form name="form">
        <?php
          require_once('recaptchalib.php');
          $publickey = "1234567"; // you got this from the signup page
          echo recaptcha_get_html($publickey);
        ?><br><br><p id="hint"></p>
        <input type="button" value="check" onclick="showHint()" />
      </form>

      <!-- more of your HTML content -->
    </body>
  </html>

gethint.php This verifies the captcha

<?php
  require_once('recaptchalib.php');
  $privatekey = "your private keys";
  $resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_GET["q"],
                                $_GET["r"]);

  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 {
  echo "Correct";
  }
  ?>

Dont forget to replace your private and public keys.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top