I have an ASP.Net MVC application that renders a form in a partial view containing a Google reCAPTCHA v2 element on page load. The page may contain one or more instances of the partial view, and we use data attributes to automatically render the reCAPTCHAs, which all works fine.
However, the form instances are posted back using a jQuery $.ajax
POST, and in the case where there are any server-side validation issues, the original partial view is re-rendered and returned to the ajax call, and the form content on the page is replaced using the jQuery replaceWith
method. This means that the original div that the reCAPTCHA was attached to has been removed from the DOM, and a new element added to it (thus losing the reCAPTCHA IFrame).
The problem is that I can't find any way in the reCAPTCHA api to either get it to re-attach to the new element (and re-render the IFrame), or to remove the original instance, and manually call grecaptcha.render
on the new element. If I try to call the render method on the new element, I get an error saying that 'reCAPTCHA has already been rendered in this element'.
Has anyone had any success on getting reCAPTCHA working on content dynamically updated via ajax?
I managed to do it by dinamically adding a random string into the id
of the element where you are wrapping your reCAPTCHA. After this I never had problem loading reCAPTCHA. You must generate this random string (let's call it token), and then use this token to create the element and later when you pass the id to render reCAPTCHA.