使用jQuery ajax进行隐形ReCaptcha [英] Invisible ReCaptcha with jQuery ajax

查看:96
本文介绍了使用jQuery ajax进行隐形ReCaptcha的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery和ajax请求在表单中实现最新的ReCaptcha(又名隐形ReCaptcha)。

ReCaptcha文档: https://developers.google.com/recaptcha/docs/invisible

I am trying to implement the newest ReCaptcha (aka "invisible" ReCaptcha) within an form using jQuery and an "ajax" request.
ReCaptcha documentation: https://developers.google.com/recaptcha/docs/invisible

我的表格:

<form id="myForm" >
    <input type="email" name="email" /><br />
    <input type="password" name="password" /><br/>
    <!--<input type="submit" value="log in" />-->
    <button class="g-recaptcha" data-sitekey="6LdK..." data-callback="onSubmit">log in</button>
</form>
<div id="status"></div>

我的javascript(jQuery):

My javascript (jQuery):

<script>

    function onSubmit(token){
        document.getElementById("myForm").submit();
    }

    $(document).ready(function(){

        $("#myForm").submit(function(event){
            event.preventDefault();
            var datas = $("#myForm").serialize();
            $.ajax({
                type: "POST",
                url: "test.php",
                data: datas,
                dataType: "json",
                    beforeSend: function(){
                        $("#status").html("logging in...");
                    },
                    success: function(response){
                        $("#status").html(response.text);
                        if(response.type=="success"){
                            window.location.replace("/myaccount");
                        }
                    },
                    error: function(){
                        $("#status").html("Failed.");
                    }
            });
        });

    });
</script>

ReCaptcha需要设置数据回调,我不知道如何与我绑定已经存在.submit(function(event)函数。

我的onSubmit()技巧不起作用,它忽略了ajax并刷新页面。


如何在datas变量中发送g-recaptcha-response值将其发送到test.php?

ReCaptcha requires to set a "data-callback", which I am not sure how to bind with my already existing ".submit(function(event)" function.
My "onSubmit()" trick did not work, it ignores the "ajax" and refreshes the page.

How do I send the "g-recaptcha-response" value within my "datas" variable to POST it to test.php?

推荐答案

所以这就是我在Invisible reCAPTCHA的文档中进一步深入研究之后的解决方法,并且学习了一些jQuery,因为我对JS(很酷的东西)不是很熟悉:

So here is how I solved it after digging further in Invisible reCAPTCHA's doc, and learning a bit of jQuery obviously since I was not very familiar with JS (cool stuff):

我的头标记带有javascript(以及一些用于删除丑陋Google徽章的css):

My head tag with the javascript (and a bit of css to remove the ugly Google badge):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl=fr" async defer></script>

<style>
    .grecaptcha-badge{
        display:none;
    }
</style>

<script>
    var onloadCallback = function(){
        grecaptcha.render("emplacementRecaptcha",{
            "sitekey": "YOUR_RECAPTCHA_SITEKEY_HERE",
            "badge": "inline",
            "type": "image",
            "size": "invisible",
            "callback": onSubmit
        });
    };
    var onSubmit = function(token){
        var userEmail = $("#userEmail").val();
        var userPassword = $("#userPassword").val();
        var userTfaOtp = $("#userTfaOtp").val();
        $.ajax({
            type: "POST",
            url: location.href,
            data:{
                    userEmail: userEmail,
                    userPassword: userPassword,
                    userTfaOtp: userTfaOtp,
                    userJetonRecaptcha: token
                },
            dataType: "json",
                beforeSend: function(){
                    $("#statutConnexion").html("Traitement de votre requête d'authentification en cours...");
                },
                success: function(response){
                    $("#statutConnexion").html(response.Message);
                    if(response.Victoire){
                        $("#formulaireConnexion").slideUp();
                        window.location.replace("/compte");
                    }
                    else{
                        grecaptcha.reset();
                    }
                },
                error: function(){
                    $("#statutConnexion").html("La communication avec le système d'authentification n'a pas pu être établie. Veuillez réessayer.");
                    grecaptcha.reset();
                }
        });
    };
    function validate(event){
        event.preventDefault();
        $("#statutConnexion").html("Validation de votre épreuve CAPTCHA en cours...");
        grecaptcha.execute();
    }
    function onload(){
        var element = document.getElementById("boutonConnexion");
        element.onclick = validate;
    }
</script>

HTML:

<div id="formulaireConnexion">
    <input type="email" name="userEmail" id="userEmail" placeholder="Courriel" title="Courriel" required="required" /><br />
    <input type="password" name="userPassword" id="userPassword" placeholder="Mot de passe" title="Mot de passe" required="required" /><br/>
    <input type="text" name="userTfaOtp" id="userTfaOtp" placeholder="Double authentification (optionnelle)" autocomplete="off" pattern="[0-9]{6}" title="Six caractères numériques" maxlength="6" /><br />
    <div id="emplacementRecaptcha"></div>
    <button id="boutonConnexion">Connexion</button>
</div>
<div id="statutConnexion"></div>
<script>onload();</script>

如果你需要整个PHP,请告诉我,因为它超出了这个问题的范围。您可能需要更改JS中的url:location.href,因为在我的情况下,渲染HTML表单的脚本和JS处理POST变量是相同的(不是很好,测试目的)。基本上我只是验证POST变量,然后最终返回一个json,如:

Let me know if you need the whole PHP as well since it's out of the scope of this question. You will probably need to change "url: location.href," within the JS above since in my case the script rendering the HTML form and the JS and dealing with the POST vars is the same (not great, testing purpose). Basically I just verify the POST vars then finally return a json like:

$jsonVictoire = true; // boolean
$jsonMessage = 'anything you want to tell your visitor'; // string

$return = 
    json_encode(
        array(
            'Victoire'=>$jsonVictoire,
            'Message'=>$jsonMessage
        )
    );
die($return);

这篇关于使用jQuery ajax进行隐形ReCaptcha的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆