Hooking into WPForms’ AJAX submission workflow for custom event handling

WPForms is a popular plugin in the WordPress ecosystem for sending forms from site visitors easily, with over 4 million active installs at the time of writing, just falling behind Contact Form 7 as the most popular. For client projects at my workplace, I prefer to use it over others thanks to it’s simple workflow with extendability when required.

Unfortunately, it doesn’t have a native integration of Google Analytics or Tag Manager to track conversions from form submissions into useful data. Their official tutorial on the matter is to purchase a plugin to handle that, and then jump through hoops to get it sending data.

On form submission, you could redirect the user to a new page that says something along the lines of “Thanks for getting in touch with us”, and let Google Analytics notice a person has landed on that page (to take it further, including the form name or ID in the URL’s query parameters). When it comes to AJAX submissions however, you won’t be able to use this method, and there’s nothing I’ve found that covers it.

Thankfully, it’s really simple to implement.

Looking through the WPForms scripts that load on the frontend, AJAX submissions make custom trigger calls to the form element on the page, listed below:

$form.trigger( 'wpformsAjaxSubmitSuccess', json );
$form.trigger( 'wpformsAjaxSubmitActionRequired', json );
$form.trigger( 'wpformsAjaxSubmitFailed', json );
$form.trigger( 'wpformsAjaxSubmitError', [ jqHXR, textStatus, error ] );
$form.trigger( 'wpformsAjaxSubmitCompleted', [ jqHXR, textStatus ] );

By added an event listener for any of these custom triggers, you can hook your script into firing a dataLayer update in your Google Tag Manager’s script, which sends data onwards to Google Analytics.

Example: Firing the ID of any successfully submitted form to Google Tag Manager:

(($) => {
  $('form.wpforms-form').on('wpformsAjaxSubmitSuccess', (event) => {
    const formId = $(event.target).attr('data-formid')
    dataLayer.push({
      'event': 'wpFormsSubmit',
      'formId': formId,
    })
  })
})(jQuery)

The event can be received in Google Tag Manager by using the Custom Event trigger, and using the name of the event from your dataLayer.push action.