2012-12-12 6 views
2

recaptcha 입력의 유효성을 검사하는 데 문제가 있습니다. Heres는 내 코드 :Ajax 오류가있는 Recaptcha

// Validate Recaptcha Input 
var challenge = $("#recaptcha_challenge_field").val(); 
var response = $("#recaptcha_response_field").val(); 

var dataString = 'recaptcha_challenge_field=' + challenge + '&recaptcha_response_field=' + response; 


var html = $.ajax({ 
type: "POST", 
    url: "PHP/recaptchaverify.php", 
    data: dataString, 
    async: true 
}).responseText; 

console.log(html); 

if(html == 'accept') 
{ 
    alert("CORRECT"); 
} 

else 
{ 
    alert("The reCAPTCHA wasn't entered correctly. Go back and try it again."); 
    $("#recaptcha_response_field").focus(); 
    Recaptcha.reload(); 
    return false; 
} 

지금 나는 지금

require_once('../scripts/recaptcha-php/recaptchalib.php'); 
$privatekey = "MYKEY"; 

$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"; 
} 

else 
{ 
    // Your code here to handle a successful verification 
    echo "accept"; 
} 

내 문제는 HTML 변수 내가 제대로 reCAPTCHA를 입력 할 때마다 "동의 함"을 표시하고있다 recpatchaverify.php 내 변수를 전달하지만, '수상 IF 문에서 작동합니까?

+0

당신이 수정 .responseText받을 수 있나요? – Jai

+0

예, .responseText가 오류를 표시하고 변수를 올바르게 승인합니다. 그냥 if else 문을 지나치는 것입니다. – Brandon

+0

if (html == "accept") <<<가 작동하지 않습니다. – Brandon

답변

1

서버에 대한 비동기 요청을하고 있습니다. 즉, $ .ajax() 라인이 완료되고 console.log() 및 if() 문으로 실행이 계속되면 서버에 대한 실제 요청은 여전히 보류 중이고 아직 완료되지 않았습니다. if() 문이 실행될 때 responseText는 실제로 '정의되지 않음'입니다.

대신,이처럼 '성공'콜백 ​​함수를 사용해야합니다 :

// Validate Recaptcha Input 
var challenge = $("#recaptcha_challenge_field").val(); 
var response = $("#recaptcha_response_field").val(); 

var dataString = 'recaptcha_challenge_field=' + challenge + '&recaptcha_response_field=' + response; 


$.ajax({ 
    type: "POST", 
    url: "PHP/recaptchaverify.php", 
    data: dataString, 
    success: function(html) { 
     if(html == 'accept') 
     { 
      alert("CORRECT"); 
     } 

     else 
     { 
      alert("The reCAPTCHA wasn't entered correctly. Go back and try it again."); 
      $("#recaptcha_response_field").focus(); 
      Recaptcha.reload(); 
      return false; 
     } 
    } 
});