简体   繁体   中英

Ajax call not working properly when used with Recaptcha

I am using PHP and AJAX together in my website to fetch data from a JSON URL and to display it on the webpage. When I use it without implementing recaptcha, it works fine but when I integrate Google's Recaptcha, the results get displayed only when the captcha puzzle is solved twice everytime. I am not sure where the bug actually lies and I even tried to implement a custom captcha and in that case also it is the same. Here is the code with recaptcha,

Captcha and Ajax code snippet :

<?php
if ($resp != null && $resp->success):  ?>

echo"hi";

<script>
$(document).ready(function(){

$("#submit").click(function(){

$.post("retrieve_train_between_stations.php", $("#get_train_running").serialize(),  function(response) {  
 $("#success").html(response);


});
return false;


});

});
</script>


<?php
else:
echo "Failed";

?>

Full code : http://pastebin.com/UynEiYng

This part should be moved to retrieve_train_between_stations.php .

require_once "recaptchalib.php";
// your secret key
$secret = "My secret key"; 
// check secret key
$reCaptcha = new ReCaptcha($secret);

$resp = false;

if (isset($_POST["g-recaptcha-response"])) {
    $resp = $reCaptcha->verifyResponse(
        $_SERVER["REMOTE_ADDR"],
        $_POST["g-recaptcha-response"]
    );
}

if ($resp) {
    //display the record
} else {
    echo 'Recaptcha can not be verified.';
}

The if/else should be removed and prevent the default event for the script

<script>
$(document).ready(function(){

$("#submit").click(function(event){
    event.preventDefault();
    $.post("retrieve_train_between_stations.php", $("#get_train_running").serialize(),  function(response) {  
 $("#success").html(response);


        });
        return false;

    });

});
</script> 

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