How to do a post request for my reCaptcha ajax api

2019-08-29 05:01发布

问题:

My reCaptcha is now implemented into my signup process using ajax..

Currently no matter what is typed in the captcha text field it never validates. It just keeps giving me new words to type in.

I've figured it's because I need to test if the user entered the right captcha answer. I need to send a POST request.

I have no idea how to do this.. I've never had to do this before and the documentation isn't clear enough for me..

I would appreciate any help I could get.

Here my code:

$(document).ready(function(){

    $('#fhjoinForm').submit(function(e) {

        register();
        e.preventDefault();

    });

});


function register()
{
    hideshow('loading',1);
    error(0);

    $.ajax({
        type: "POST",
        url: "submit.php",
        data: $('#fhjoinForm').serialize(),
        dataType: "json",
        success: function(msg){

                if(parseInt(msg.status)==1)
                {
                Recaptcha.create("pub key xxxxxxxxxxx",
               "recaptcha_div",
                {
                theme: "clean",
                callback: function(){
                // what to do on success
                window.location=msg.txt;
         }

            }

     );
   }

            else if(parseInt(msg.status)==0)
            {
                error(1,msg.txt);
            }

            hideshow('loading',0);
        }
    });

}


function hideshow(el,act)
{
    if(act) $('#'+el).css('visibility','visible');
    else $('#'+el).css('visibility','hidden');
}

function error(act,txt)
{
    hideshow('error',act);
    if(txt) $('#error').html(txt);
}

This is for my post request

<?php
require_once('recaptchalib.php');
$publickey = "pub key hidden"; // you got this from the signup page
$privatekey = "priv key hidden";

$resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

if ($resp->is_valid) {
    ?>success<?
}
else 
{
    die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
       "(reCAPTCHA said: " . $resp->error . ")");
}
?>

回答1:

Your jQuery code looks like it's creating the reCAPTCHA after the form is submitted, because it's creating it in the success() function after PHP has tried to validate. But really, the reCAPTCHA should be created and displayed first.

Then on the form submit run register and let PHP check the value.

  1. Display reCAPTCHA and wait for user to submit
  2. Send AJAX to PHP and let recaptcha_check_answer do it's job
  3. Display the error or success to the user.