4

I have a gravity form that is being loaded by an AJAX function. For some reason, when I try to submit the form I get a 400 error /wp-admin/admin-ajax.php#gf_3:1

Following guides online I added gravity_form_enqueue_scripts(3, true); to my header.php which has not solved the issue.

The form works fine in the preview page. I've tested multiple forms and multiple functions, however none of my forms will submit if they were loaded via AJAX.

Enrico Cortinovis
  • 811
  • 3
  • 8
  • 31
laudx
  • 43
  • 4

2 Answers2

4

I spent many hours on this problem. I'm using Gravity Forms 2.5.1

It turns out that the `DOMContentLoaded' event that is loaded with the form was not being triggered.

In my function that calls the form, I manually triggered the event and now it works as expected.

    window.document.dispatchEvent(new Event("DOMContentLoaded", { bubbles: true, cancelable: true }));```
Squivo
  • 917
  • 1
  • 10
  • 21
  • 1
    Why does this happen, should it be reported to GF? – Klaudio Milankovic Aug 23 '21 at 09:40
  • 2
    https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event --- It's fired only on the initial htm load, so GF has been assuming that it will fire when it won't ( always )... I suppose it should be reported to GF, good idea – Squivo Aug 24 '21 at 17:34
0

I have the same issue and stumbled on your question here. I am loading different forms on the same page via ajax and I think I've found the solution.

You need to localize ajax.url

wp_localize_script( 'change-this-to-your-theme-handle', 'ajax', array(
    'url' => admin_url( 'admin-ajax.php' )
));

Looks like GF is looking for this if the form is loaded with ajax. I think they just assume that if you loaded GF with ajax that you are using ajax.url. Instead I was using my own object to localize stuff which is probably what you did too.

  • Hi Klaudio, i don't understand your mind by "change-this-to-your-theme-handle"! How i know wht is my theme-handle please?! – thống nguyễn Jul 29 '21 at 04:40
  • 1
    Your theme handle is whatever you used to register another script. For example when enqueuing script the second parameter in that function is the handle. Check it out here https://developer.wordpress.org/reference/functions/wp_localize_script/ Scroll down to comments to see the demo code. – Klaudio Milankovic Aug 12 '21 at 12:14