DEV Community

Discussion on: Adding reCaptcha v3 to a Rails app without a gem

Collapse
 
benjp profile image
Ben

Hi Felice, great article!

I'm handling my forms with ajax (remote: true) and I'm struggling to figure out how I can reset the recaptcha after a successful post. Any help would be appreciated :)

Thanks,
Ben

Collapse
 
jeremylopez profile image
Jeremy Lopez

I know this is a little late but I just had to solve this problem so hopefully my response can help someone else. Basically, since my form is a create action, I edited my create.js file to update the token on failed submission. Here's how:

Here's a portion of my form where I render a partial that include my captcha tag:

...

<div class="col-12">
  <div class="form-group captcha captcha-lead_creation_modal">
    <%= render "potential_clients/captcha_field", action: 'lead_creation_modal' %>
  </div>
</div>

<div class="col-lg-12 d-flex m-t-20">
  <%= f.submit 'Request More Information', class: "btn btn-md btn-block btn-info-gradiant" %>
</div>

Here's the complete partial: potential_clients/captcha_field:

<%= recaptcha_execute(action) %>

Finally, in my create.js I do the following:

// other error handling / success code goes here

$(".captcha-lead_creation_modal").html("<%= j render 'potential_clients/captcha_field', action: 'lead_creation_modal' %>")

This will re-render the portion of the form with the token and since it hits the helper function, a new token is generated!

Collapse
 
morinoko profile image
Felice Forby

Nice! Thank you so much for sharing your solution!

Collapse
 
morinoko profile image
Felice Forby

Hi Ben, thanks for reading!

Unfortunately, I've never done the resetting with ajax myself, so I can't give you any tips from my own experience. I was just checking out some other blogs and the google documentation, though, and you might be able to use the reCaptcha javascript api and reset it with grecaptcha.reset(widgetId);. This blog post mentions it but not sure if it works.