Is there a way to invoke a function once grecaptcha.execute() has completed running, but in response to a particular event?

Presently, the JavaScript function grecaptcha.execute is triggered on page load, as shown in the first example below. This means that the reCAPTCHA challenge occurs as soon as the page loads. A more ideal scenario would be to trigger it when the form submit button is clicked instead. I attempted this by moving the execution into the submit event (as shown in the second JS example) and placing the axios function within a promise. However, it seems that the form is being submitted before the grecaptcha.execute completes its execution.

What am I missing here? This is my initial encounter with promises, so perhaps I don't quite understand how they operate? Is there a better solution for this issue? Or could it be something else entirely?

HTML

<head>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" defer></script>
</head>

JS

const form = document.querySelector('#subscribe');
let recaptchaToken;
const recaptchaExecute = (token) => {
    recaptchaToken = token;
};


const onloadCallback = () => {
    grecaptcha.render('recaptcha', {
        'sitekey': 'abcexamplesitekey',
        'callback': recaptchaExecute,
        'size': 'invisible',
    });
    grecaptcha.execute();
};

form.addEventListener('submit', (e) => {
    e.preventDefault();
    const formResponse = document.querySelector('.js-form__error-message');
    axios({
        method: 'POST',
        url: '/actions/newsletter/verifyRecaptcha',
        data: qs.stringify({
            recaptcha: recaptchaToken,
            [window.csrfTokenName]: window.csrfTokenValue,

        }),
        config: {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        },
    }).then((data) => {
        if (data && data.data.success) {
            formResponse.innerHTML = '';
            form.submit();
        } else {
            formResponse.innerHTML = 'Form submission failed, please try again';
        }
    });
}

JS

const onloadCallback = () => {
    grecaptcha.render('recaptcha', {
        'sitekey': 'abcexamplesitekey',
        'callback': recaptchaExecute,
        'size': 'invisible',
    });
};

form.addEventListener('submit', (e) => {
    e.preventDefault();
    const formResponse = document.querySelector('.js-form__error-message');
    grecaptcha.execute().then(axios({
        method: 'POST',
        url: '/actions/newsletter/verifyRecaptcha',
        data: qs.stringify({
            recaptcha: recaptchaToken,
            [window.csrfTokenName]: window.csrfTokenValue,
        }),
        config: {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        },
    })).then((data) => {
        if (data && data.data.success) {
            formResponse.innerHTML = '';
            form.submit();
        } else {
            formResponse.innerHTML = 'Form submission failed, please try again';
        }
    });
}

Answer №1

Utilizing a web service to have a universal method across all pages has been my preferred approach. It is crucial to note the necessity of returning false and triggering a post back upon the completion of the ajax request.

<script type="text/javascript>

   function VerifyCaptcha()
    {
        grecaptcha.ready(function () {
            grecaptcha.execute('<%#RecaptchaSiteKey%>', { action: 'homepage' }).then(function (token) {
            $.ajax({
                type: "POST",
                url: "../WebServices/Captcha.asmx/CaptchaVerify", 
                data: JSON.stringify({ 'captchaToken' : token }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    __doPostBack('<%= RegisterButton.UniqueID%>', '');
                    //console.log('Token verification successful');
                },
                failure: function (response) {                     
                    //alert(response.d);
                }
                });
            });
       });

       return false;
    }

</script>

Answer №2

To address this issue, I made a simple change by converting the submit button into a basic button and managing everything within a JavaScript function:

@Html.HiddenFor(model => model.ReCaptchaToken);

<input type="button"
        value="Submit"
        onclick="onSubmit()"
/>

The 'then()' method waits for the token, places it in a hidden field, and only then proceeds to manually submit the form:

<script>
    if (typeof grecaptcha == 'object') { // This may be undefined behind certain firewalls
        grecaptcha.execute('@Config.ReCaptchaSiteKey', { action: 'register' }).then(function (token) {
            window.document.getElementById('ReCaptchaToken').value = token;
            $('form').submit();
        });
    } else {
        window.document.getElementById('ReCaptchaToken').value = -1;
        $('form').submit();
    }
</script>

Keep in mind: @Html.HiddenFor is specific to MVC - you may not need that. $('form') pertains to JQuery - although you can also use getElementById instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can the hreflang tag be used correctly in a React application that supports multiple languages?

I have a React application with 3 pages(routes) and I support 2 languages (English and Spanish). Should I insert the following code into the <head></head> section of the public\index.html file like this? <link rel="alternate" ...

Is there a way to identify the source of a div's scrolling behavior?

While working on a complex web page that involves multiple JQuery Dialogs and other widgets, I encountered a frustrating issue. Some of the dialogs contain divs with scrolling abilities (using overflow-y with a fixed height). Whenever I click on one dialog ...

Leveraging Vue.js to preload data with client-side rendering

When it comes to server-side rendering in Vue, like with Nuxt, the process involves grabbing data using the serverPrefetch() function and rendering content on the server side. This allows for the request to return data to the user only after the initial do ...

Guide to generating customized CSS styles on-the-fly in Vue (similar to Angular's dynamic styling capabilities)

When working with Angular, we have the capability to dynamically set CSS properties. For example: <style ng-if="color"> .theme-color { color: {{color}}; } .theme-background-color { background-color: {{color}}; } .theme-border-color { border-color: { ...

Accessing the web3 attribute from the React-Web3 provider to enhance functionality

I'm struggling to understand the basic functionality of react-web3-provider My component structure is as follows: import React, { Component } from "react" import { withWeb3 } from 'react-web3-provider'; import Web3 from 'web ...

Is commenting required? Well, meteor!

I am currently developing a chat application using Meteor and I am facing an issue where I want to require users to type something before sending a message (to prevent spamming by hitting enter multiple times). Unfortunately, I am unsure of how to achieve ...

Using tokens to make consecutive API calls in JavaScript/Node.js

After generating the token, I need to make sequential calls to 5 different APIs. The first API used to generate the token is: POST https://idcs-xxxx.identity.c9dev2.oc9qadev.com/oauth2/v1/token Using the username and password, I will obtain the token from ...

Replace the term "controlled" with "unleashed" when utilizing the file type input

In my app, I have defined multiple states like this: const [state,setstate]=React.useState({headerpic:'',Headerfontfamily:'',Subheaderfontfamilty:''}) And to get an image from my device, I am using the following input: &l ...

The script from '*' is being denied execution because its MIME type ('application/json') is not executable, and a strict MIME type check is in place

Here is the code I used to retrieve data from the confluence rest api: <script type="text/javascript" src="Scripts/jquery.min.js"></script> <script> $.ajax({ type: "GET", url: "https://blog.xxxxx.com/rest/api/content? ...

How does combineReducers in Redux determine which specific portion of the application state to send to the reducer?

While going through the Redux basics tutorial, I found myself a bit confused about how the code snippet below determines which part of the application state should be passed to each reducer mentioned in the combineReducers function. Does it simply rely o ...

Extract several "documents" from one compilation

To easily convert my code into a single module using webpack, I can use the following method: { entry: path.join(__dirname, 'src/index.js'), output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', ...

Is it possible to retain various delimiters after dividing a String?

In the code below, the someString gets split into an array using specified delimiters in separators var separators = ['\\.', '\\(', '\\)', ':', '\\?', '!&apos ...

Convert JSON data into a Google chart with a dynamic number of columns and arrays

Modify my variable chart which currently holds this JSON: [{ "month": "January", "values": [0, 0, 0, 0, 0, 0, 0, 0, 0] }, { "month": "February", "values": [0, 0, 0, 0, 0, 0, 0, 0, 0] }, { "month": "March", "values": [35, 3, 8, 18, ...

Extracting data from websites using Python's Selenium module, focusing on dynamic links generated through Javascript

Currently, I am in the process of developing a webcrawler using Selenium and Python. However, I have encountered an issue that needs to be addressed. The crawler functions by identifying all links with ListlinkerHref = self.browser.find_elements_by_xpath( ...

The information seems to not be getting transferred to the req.body variables from the HTML form

Within my server-side settings using knex and express, I have defined the following function: // POST: Create new users app.post('/add-user', (req, res) => { const {firstName, lastName, emailAdd, gender, dob, password} = req.body; cons ...

Preserve HTML element states upon refreshing the page

On my webpage, I have draggable and resizable DIVs that I want to save the state of so they remain the same after a page refresh. This functionality is seen in features like Facebook chat where open windows remain open even after refreshing the page. Can ...

Interfacing with Ajax to dispatch information to a PHP script

Hello, I'm currently working on implementing Ajax in my web application. However, I've encountered a small issue. I'm attempting to check if a username has already been registered by controlling a form. The problem arises when my JavaScript ...

What sets apart getStaticProps + fallback:true from getServerSideProps?

I have gone through the Next.js documentation multiple times, but I am still struggling to grasp the difference between using getStaticProps with fallback:true and getServerSideProps. From my understanding: getStaticProps getStaticProps is rendered at b ...

Discover the method for displaying a user's "last seen at" timestamp by utilizing the seconds provided by the server

I'm looking to implement a feature that displays when a user was last seen online, similar to how WhatsApp does it. I am using XMPP and Angular for this project. After making an XMPP request, I received the user's last seen time in seconds. Now, ...

Tips on using jQuery to horizontally align an element in the viewport

Although this question has been raised before, my situation is rather unique. I am currently constructing an iframe for future integration into a slideshow component on the website. The challenge lies in the fact that I have a dynamically sized flexbox th ...