Ensure that the postback in ASP.net is triggered only after waiting for a promise to be resolved

Currently working on integrating v3 recaptcha into my asp.net webforms page.

The issue I'm facing is that it seems like grecaptcha.ready operates asynchronously, causing the page to postback immediately without waiting for the client event to complete.

Is there a way to make the postback pause until grecaptcha.ready and grecaptcha.execute are finished?

Here's the front-end code snippet:

 <script src="https://www.google.com/recaptcha/api.js?render=key"></script>
     <script>
         function onbtnRegistrazioneClick(e) {  
        
             return grecaptcha.ready(function () {
                 grecaptcha.execute('key', { action: 'submit' }).then(function (token) {
                     console.log(token);
                     document.getElementById("gRecaptchaResponse").value = token;
                    
                 });
             });
            
         }
     </script>

<asp:Button runat="server" ID="btnRegistrazioneCliente" CssClass="btnGenerico" Text='<%$ Resources:btnRegistratiText%>' ValidationGroup="NewUtente" CausesValidation="true" OnClientClick="onbtnRegistrazioneClick(event);"></asp:Button>
<input type="hidden" value="" id="gRecaptchaResponse" name="gRecaptchaResponse" />

And here's the back-end code snippet:

 Public Sub btnRegistrazioneCliente_Click(sender As Object, e As System.EventArgs) Handles btnRegistrazioneCliente.Click 'btnRegistrazioneCliente.ServerClick '
        If Me.IsValid Then 

            Dim gRecaptchaResponse As String = Request.Form("gRecaptchaResponse")
            Dim isCaptchaValid As Boolean = Globals.Security.ReCaptchaV3.Validate(gRecaptchaResponse)
        '...

        else

        '...

        end if 

 End Sub

Answer №1

Here is my solution:

__doPostBack('<%=btnSubmitForm.UniqueID%>', 'OnClick');   

 <script>
         function handleBtnClick(e) {  
        
             return grecaptcha.ready(function () {
                 grecaptcha.execute('6Ld2D1MbAAAAAMwnZ4iN1p1G9K7YQWdQW84nNQjv', { action: 'submit' }).then(function (token) {
                 
                     document.getElementById("gRecaptchaResponse").value = token;
                     __doPostBack('<%=btnSubmitForm.UniqueID%>', 'OnClick');
                 });
             });
            
         }
     </script>

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 I change an array from OData into JSON format?

I've been working on finding a solution to properly handle an OData response in JavaScript. The issue I am facing is that the response comes back formatted as an array rather than JSON, preventing me from using JSON.parse(mydata) with the current data ...

The new Model.save() method in Mongoose v6.2.7 is experiencing issues and none of the attempted solutions such as promises, callbacks, or async await in try

At first, the project was established to support promises, and all queries utilized promise-like methods such as method.then().catch(). However, some were later switched to try-catch with async await. Everything functioned properly until a few weeks ago wh ...

How can I automatically disable certain checkboxes when a specific radio button is selected?

Looking to disable certain checkboxes when a specific radio button is selected. For instance, selecting the first radio button with the id="pz1" should disable checkboxes with matching id values from the thisToppings array. Each radio button cor ...

Striped artifacts can be observed in the lights of A-Frame technology, with their appearance varying depending

I'm currently using A-Frame version 1.0.4 and have experimented with both spotlights (as shown in the attached image) and direct light sources. Adjusting the shadowBias to -0.0001 only minimally impacts the artifact issue. By setting shadowMapHeight ...

Removing an object in Three.js using scene.getObjectByName() method

When developing my game, I encountered a challenge. I'm loading 4 different buildings and creating 15 clones of each within a for loop. These clones are then added to an array called masterBuildingArray, which I iterate through using a forEach loop. T ...

Issues with Fetch and Axios in React Native are causing functionality to be limited

For 3 different projects, I have been attempting to get fetch or axios to work without success. I've tried adjusting the android manifest as suggested in some troubleshooting threads, but nothing seems to be working. Whether using await/async, promise ...

Ways to extract text solely from the parent element, excluding any content from the child elements

I need to extract just the text updated page title from the following code snippet <h2 class="cmp-title__text" xpath="1"> updated page title <span class="gmt_style" aria-hidden="true"&;gt; ...

Building interactive tables with dynamic columns using Datatables.net

We have successfully implemented datatables with MVC 4 for static columns, thanks to datatables. Our current challenge lies in dynamically generating the datatables table. For instance, our model includes a list of columns:- public class SampleModel ...

Unique color selection for progress bars in Bootstrap Vue

Can the color of a progress bar be customized to any specific value in hexadecimal format? The preset colors like 'success' or 'danger' are not meeting our requirements, so I need to define my own color for the progress bar using a hex ...

Angularfire2 throws an error with the message, "app/bad-app-name," when using Firebase

Encountering an error in my Angular app where Firebase is returning a code bad-app-name. The app utilizes angularfire2 within the Angular framework. After verifying the Firebase configuration and confirming it is correct, how can this error be resolved? ...

What is the best way to insert a value into the span element generated by the Tag-it plugin?

Currently working with the Tag-it plugin to generate tags. Since the tags are created using spans, I'm curious to learn how I can assign a value to a tag created by the plugin? Seeking assistance from someone knowledgeable in this area. Thank you! ...

Is there a way to automatically input an array of elements into a form without having to do it manually

Is it possible to create a form using an array of items fetched from a database, and automatically populate the form with each of these elements? Currently, I'm facing difficulties as the form appears empty. What am I missing? Below is the code I ha ...

Visualization with D3 - Putting an image at the heart of a circular chart made with SVG

Is it possible to add an image to the center of a donut SVG in D3 charts using JavaScript? I've been attempting to achieve this but haven't had any success so far. Currently, I have inserted the image in HTML, but it does not align with the cent ...

What are some possible explanations for why a JavaScript breakpoint may not be triggering?

While working on a razor view, I decided to set a breakpoint in a script block. When using VS2012 and attaching to IE, I noticed that the breakpoint had a yellow triangle with an exclamation mark, indicating the message: The breakpoint will not currentl ...

Is it possible to detect a swipe event without relying on third-party libraries

Is there a way to detect a swipe instead of a click using only pure jQuery, without relying on jQuery Mobile or external libraries? I've been examining the TouchSwipe source code, but it contains a lot of unnecessary code for what I really need - sim ...

How can I restrict the draggable space? It is only working on the top and left sides, but I want to disable it on the right and bottom

Attempting to prevent the draggable items from overflowing beyond the body. Succeeded in limiting movement on the top and left sides. Encountering difficulty restricting motion on the right side and bottom. e.pageX -= e.offsetX; e.pageY -= e.offsetY; ...

Implementing a controller's method within a jQuery/ajax URL in Rails: A step-by-step guide

My goal is to use jQuery/Ajax to create and save data in the cart model by calling the controller's method in the Ajax URL. Here's the jQuery/Ajax script: $(document).ready(function() { $('.add-cart-product').click(function() { va ...

What is preventing the audio from playing in Safari?

Recently, I developed a small JavaScript program that is meant to play the Happy Birthday tune. This program utilizes setInterval to gradually increase a variable, and depending on its value, plays or pauses certain musical notes. However, I encountered ...

Validating Forms in AngularJS: Ensuring At Least One Input Field is Not Empty

Consider the following basic HTML form: <form name="myForm" action="#sent" method="post" ng-app> <input name="userPreference1" type="text" ng-model="shipment.userPreference" /> <input name="userPreference2" type="text" ng-model="shipm ...

JavaScript image sorting function fails to sort multiple ID elements that match

Currently, I am working on a project to develop an image sorter using toggle buttons. However, I have encountered an issue where my function is only effective for the first image ID and not any others. Below is the JavaScript function in question: functi ...