简体   繁体   中英

PHP Google reCAPTCHA with AJAX not working

I have form in 100.php with ajax call to 200.php.

<html>
<head>
    <!-- include reCAPTCHA API JavaScript library given by Google -->
    <script src='https://www.google.com/recaptcha/api.js'></script>

     <script type="text/javascript" 
     src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script>
  $(document).ready(function() {            
    $("#btn").click(function(event){
       event.preventDefault();

        var myname = $("#name").val();
        var myaddress = $("#address").val();
        var yourData ='name='+myname+'&address='+myaddress; // php is expecting name and age
        $.ajax({
          type:'POST',
          data:yourData,//Without serialized                
          url: '200.php',
          success:function(data) {
             if(data){
                $('#testform')[0].reset();//reset the form
                $('#result').html(data); // here html()
                //alert('Submitted');
             }else{
                return false;
              }                        
           }
         });

        });             
     });
</script>
</head>
<body>


    <form method="post" id="testform">
        Name: <input type="text" name="name" value="" id="name"/> <br />
        Address: <input type="text" name="address" value="" id="address"/>
        <!-- 
            place for the reCAPTCHA widget div with your site key 
            data-theme="dark" attribute - gives dark version
        -->
        <div class="g-recaptcha" data-sitekey="6LeJ8h8TAAAAAMS9nQX89XccpsC-SDeSycipiaHN"></div>
        <input type="submit" name="ok" value="Send" id="btn"/>
    </form>
    <div id='result'></div>

</body>

200.php does validate captcha and diaplay name and adddress user entered. But my problem is that when I entered name and address, click on captcha. Captha is also validated and shows as in my screenshot. but name and address is not shown on the page. You can also check yourself here: http://raveen.comlu.com/100.php

I am new to Ajax call by PHP. I googled and I can troubleshoot by firebug. Can you say what I am doing wrong here? and steps to troubleshoot by firebug like to check if my ajax call is done, etc? thanks for your help.

Note: when I put all these code in one page without using ajax call. it works fine!!!!! I want this happens without page reload....

output

200.php

<?php
    require_once('recaptchalib.php');

    if( isset($_POST['ok']) ){

        if( isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']) ){
            $secret = "6LeJ8h8TAAAAAB3IFQVQEaoApFe6lvq4Wxlktvn1"; //your secret key
            $response = null; //empty response
            $reCaptcha = new ReCaptcha($secret); //check secret key is present

            $response = $reCaptcha->verifyResponse( $_SERVER['REMOTE_ADDR'], $_POST['g-recaptcha-response'] );

            //$response variable will report back with "success"
            if( $response!=null && $response->success ){
                echo "<h1>Hi ". $_POST['name']. " from ". $_POST['address']. ", thanks for submitting the form!</h1>";
            }
        }
        else{
            echo "<h1>Please click on the reCAPTCHA box.</h1>";
        }
    }

?>

There are few errors in your code, such as:

  • Look at the following two statements,

     if( isset($_POST['ok']) ){... 

    and

     var yourData ='name='+myname+'&address='+myaddress; 

You're not sending any variable named ok to 200.php page, so the control won't even enter the if block.

If your website performs server side validation using an AJAX request, you should only verify the user's reCAPTCHA response token ( g-recaptcha-response ) once. If a verify attempt has been made with a particular token, it cannot be used again. You will need to call grecaptcha.reset() to ask the end user to verify with reCAPTCHA again.

So you have to use grecaptcha.getResponse() to get the user's response.

And as a sidenote use grecaptcha.reset() to ask the end user to verify with reCAPTCHA again.

Your jQuery/AJAX script should be like this:

<script>
    $(document).ready(function() {            
        $("#btn").click(function(event){
            event.preventDefault();

            var recaptchaResponse = grecaptcha.getResponse();

            var myname = $("#name").val();
            var myaddress = $("#address").val();
            var yourData = {name: myname, address: myaddress, recaptchaResponse: recaptchaResponse};
            $.ajax({
                type: 'POST',
                data: yourData,
                dataType: 'html',
                url: '200.php',
                success: function(data) {
                    // reset form
                    $('#testform')[0].reset();

                    // display data
                    $('#result').html(data);

                    // reset the reCaptcha
                    grecaptcha.reset();
                },
                error: function(jqXHR, textStatus, errorThrown){
                    // error
                }
            });
        });             
    });
</script>

And on 200.php page, process your AJAX data like this:

<?php

    //your site secret key
    $secret = '6LeJ8h8TAAAAAB3IFQVQEaoApFe6lvq4Wxlktvn1';

    if(isset($_POST['recaptchaResponse']) && !empty($_POST['recaptchaResponse'])){
        //get verified response data
        $param = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['recaptchaResponse'];
        $verifyResponse = file_get_contents($param);
        $responseData = json_decode($verifyResponse);

        if($responseData->success){
            // success
            echo "<h1>Hi ". $_POST['name']. " from ". $_POST['address']. ", thanks for submitting the form!</h1>";
        }else{
            // failure
            echo "<h1>You have incorrect captcha. Please try again.</h1>";
        }

    }else{
        echo "<h1>Please click on the reCAPTCHA box.</h1>";
    }

?>

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