Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

Plugins

How to AJAX form with recaptcha?

form

Started by ontime 7 years ago · 9 replies · 1931 views
7 years ago

Hi,

My forms were working fine with AJAX based on this document: https://learn.getgrav.org/16/forms/forms/how-to-ajax-submission

But since some recent updates, the AJAX part ceased to work. Now after submission of the form, the whole page is reloaded and the response message appears alone on this empty page.

When I disable the captcha, things work fine.

After some testing:
It works with Grav v1.6.19 and Form v3.0.8.
But fails when I update to Form v4.0.0.

last edited 12/20/19 by ontime
4 years ago

I use reCaptcha v2 (checkbox) on my page with Form plugin v6.0.0 and it works just fine with Ajax form 🤔 I remember it took a while to implement Ajax form in the module page overall, but there's no issue now

👍 1
4 years ago

@Karmalakas, Sounds great! Would you mind sharing your code and also update the issue on Github?

4 years ago

I don't think I have anything special there. Just handling of submit to re-render the response 🤔

Frontamatter of the form page (a bit stripped down):

YAML
visible: false
debugger: false
sitemap:
    ignore: true
form:
  name: contact-form
  action: '/form'
  client_side_validation: false
  inline_errors: true
  keep_alive: true

  fields:
    -
      id: contact-name
      name: name
      label: CONTACT_FORM.NAME.LABEL
      autocomplete: true
      type: text
      validate:
        required: true
    -
      id: contact-email
      name: email
      label: CONTACT_FORM.EMAIL.LABEL
      type: email
      validate:
        required: true
        type: email
    -
      name: g-recaptcha-response
      type: captcha
      label: Captcha

  buttons:
    -
      type: submit
      value: CONTACT_FORM.BUTTON.SUBMIT

  process:
    -
      captcha: true
    -
      message: CONTACT_FORM.THANK_YOU
    -
      reset: true

In modular.html.twig:

TWIG
{% include "forms/ajax-form-wrapper.html.twig" with {form_page: page.find('/form')} %}

ajax-form-wrapper.html.twig:

TWIG
{% do assets.addJs('jquery', 101) %}
{% do assets.addJs('https://cdn.jsdelivr.net/gh/cferdinandi/[email protected]/dist/saferInnerHTML.min.js', 50) %}
{% do assets.addJs('theme://js/form.min.js', 25) %}

{% set form_page = form_page ?? page %}
{% set page_form = page_form ?: (forms({"route": form_page.route}) ?: forms('contact-form')) %}

{% if page_form %}
    <div id="form-result-{{ page_form.name }}" class="text-left">
        {% include "forms/form.html.twig" with {form: page_form} %}
    </div>
    <script>
        $(function () {
            bindAjaxFormSubmit('{{ page_form.name }}', '{{ uri.base ~ uri.uri }}');
        });
    </script>
{% endif %}

form.js:

JS
function ajaxReq() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        return new ActiveXObject('Microsoft.XMLHTTP');
    } else {
        alert('Browser does not support XMLHTTP.');

        return false;
    }
}

function bindAjaxFormSubmit(id, page_url) {
    page_url = page_url || window.top.location.href;
    const xhr = ajaxReq();
    const responseHolder = document.getElementById('form-result-' + id);

    document.getElementById(id).addEventListener('submit', function (e) {
        e.preventDefault();
        this.querySelector('button[type="submit"]').disabled = true;

        xhr.open(this.getAttribute('method'), this.getAttribute('action'), true);
        xhr.send(new FormData(this));

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                saferInnerHTML(responseHolder, xhr.response);
                bindAjaxFormSubmit(id, page_url);
            }
        }
    }, false);
}

Part of form.yaml:

YAML
recaptcha:
  version: 2-checkbox

Not sure what I should update on GitHub issue 🤔

👍 1
4 years ago

@Karmalakas, Thanks!

I use reCaptcha v2 (checkbox) on my page with Form plugin v6.0.0 and it works just fine with Ajax form

You make it sound as if adding reCaptcha to the Ajax tutorial mentioned before is a piece of cake and is working fine. However, your code seems quite complex...

Is all of your code needed to get reCaptcha to work instead of merely adding a captcha field and process field?

4 years ago

IIRC, this all code and additional template was needed just to make Ajax work in modular page and has nothing to do with reCaptcha itself. It's been a couple of years now I think, so my memory might play tricks, but I'm pretty sure this is the case 🙂 And with this approach I can now add my Ajax form wherever I want

Suggested topics

Topic Participants Replies Views Activity
Plugins · by Rene, 1 week ago
2 41 1 week ago
Plugins · by Xavier, 4 weeks ago
2 50 4 weeks ago
Plugins · by Luka Prinčič, 7 years ago
3 1178 1 month ago
Plugins · by Sebastian van de Meer, 1 month ago
1 45 1 month ago
Plugins · by PIERROT Alain, 2 months ago
3 68 2 months ago