简体   繁体   中英

Ajax post always results in error, even though everything seems correct

I'm trying to process captcha in form validation using google's reCaptcha. Basically, my validation function is called using onSubmit in the form tag, and then calls a second function to work with the recaptcha api.

Here's the code:

        var returnValue;

        var myData = {
            privatekey  : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
            remoteip : ip,
            challenge : challenge,
            response : response
        };

        $.ajax({
            url: "http://www.google.com/recaptcha/api/verify",
            type: "POST",
            data: JSON.stringify(myData),
            dataType: "text",
            success: function(data) {
                var result = data.split("\n");
                if (result[0] == "true") {
                    returnValue = true;
                }
                else {
                    returnValue = false;
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                alert("There was an error submitting the captcha.  Please contact an administrator. \n\nError:\n" + textStatus, errorThrown);
                returnValue = false;                    
            },
            complete: function(jqXHR, textStatus) {
                return returnValue;
            }
        });

Using LiveHTTPHeaders in firefox, I can see the request go out to the service, and it looks like everything is being sent correctly. I get an HTTP/1.1 200 OK response back, and yet every single time the code goes to the error function. When the error function runs, jqXHR is:

Object { readyState=0, status=0, statusText="error"}

textStatus is "error", and errorThrown is ""

I've tried doing this a number of ways, including $.POST, and using .done(), .fail(), .always(), and it always behaves the same.

I've seen some other postings here having to do with problems with cross-domain requests, but none of those situations really seem to be relevant, because I actually am doing a cross-domain request, and those seemed to be issues where they were making requests to a file on the same domain, and it was being handled incorrectly as a cross-domain request.

I'm at my wits end here.. any help would be greatly appreciated.

I've seen some other postings here having to do with problems with cross-domain requests, but none of those situations really seem to be relevant, because I actually am doing a cross-domain request

When I run that code I get the error:

XMLHttpRequest cannot load http://www.google.com/recaptcha/api/verify.
Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.

So it is a cross-domain issue. You might want to make a cross domain request, but Google isn't set up to allow it.

I'm pretty sure that recaptcha needs to be implemented with server side code. If you do it entirely on the client with JS then the client can lie and say it has passed the captcha when it hasn't.

function check(){
    $.post('check.php',{
        'check':1,
        'challenge':$('#recaptcha_challenge_field').val(),
        'response':$('#recaptcha_response_field').val()},
        function(a){
            console.log(a);
        });
}

check.php:

if($_POST){
    if(isset($_POST['check'])){
        $url = 'http://www.google.com/recaptcha/api/verify';

        $data = array(
            'privatekey'=>  "**********************************",
            'remoteip'  =>  $_SERVER['REMOTE_ADDR'],
            'challenge' =>  $_POST['challenge'],
            'response'  =>  $_POST['response'],
        );
        $options = array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data),           
            ),
        );
        echo print_r($data,true);
        die(file_get_contents($url, false, stream_context_create($options)));
    }
}

Warning: You have only one choice to check! ( Ref. )

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