FreeGoogle Tag Manager recipes

Track Gravity Forms Submissions in Google Tag Manager with this Free GTM Recipe

A free, tested Google Tag Manager recipe that captures Gravity Forms submissions and turns them into a trigger you can use to fire conversions to Google Ads, Google Analytics and more.

Aaron Beashel
Aaron BeashelUpdated July 20267 min read
The Gravity Forms recipe tag inside Google Tag Manager

Google Tag Manager is a common way to send conversions to Google Ads, Google Analytics, etc when someone submits a Gravity Form on your website.

The problem is, it's quite difficult to set up. Gravity Forms uses AJAX to save form submissions, which means Google Tag Manager's built-in form submission trigger doesn't work, so you're left having to write custom code to detect the form submission, send an event to the dataLayer, and build a trigger on top of that.

And unless you're a developer or very experienced with Google Tag Manager, you're going to struggle.

Fortunately though, there is a simple solution.

You can simply install this Gravity Forms Conversion Tracking Recipe in your Google Tag Manager account and you'll have everything you need to get basic conversion tracking set up.

What Is a Google Tag Manager Recipe and What's in It?

A recipe is a pre-built bundle of Google Tag Manager assets (a tag, a trigger and a variable) that you import in one go instead of building each piece yourself. You can see all our recipes and how they work in the GTM recipe library.

This recipe detects Gravity Forms submissions, sends a 'Form Submitted' event to Google Tag Manager, and gives you a Trigger you can use to send conversions to Google Analytics, Google Ads, etc. There are three parts to it, and nothing inside is hidden. Here's exactly what each piece contains, so you can see what you're importing before you import it.

Custom HTML Tag

Listens for successful Gravity Forms submissions and pushes a 'gravity_form_submitted' event to the dataLayer. To confirm each submission was accepted before any redirect happens, it asks Gravity Forms to send the final submission using its own AJAX method. Your saved form settings stay exactly as they are. It fires on All Pages, once per event, and this is the code inside it.

The Tag's CodeJavaScript · 229 lines
/* Gravity Forms Submission Listener by Converly.
 * Event-only adaptation of verified production detection helpers.
 * Source SHA256 3ed591d48dc449e94fd48f634bb07ae8285f5d661a4b48fc5db867ca3e659b69.
 * Reads no form field values. Sends only event and form_id to dataLayer.
 * Native handoff stores only form ID, source path and time in sessionStorage.
 */
(function(){
"use strict";
if(window.__converlyGalleryGravityForms)return;
window.__converlyGalleryGravityForms=true;
// Preserve the original recipe guard for an old recipe loaded after this code.
// Do not return on the legacy guard: an old-first listener is independently
// active and remains an unsupported migration state, but must not suppress us.
window.__converlyRecipeGravityForms=true;
function isGravityForm(formEl) {
    if (!formEl) return false;
    // Check for gform_wrapper parent or gform_ ID prefix
    try {
      if (formEl.closest && formEl.closest('.gform_wrapper')) return true;
    } catch (e) {
      // .closest not available — fall back to ID check
    }
    // Fallback: GF forms have IDs like "gform_1", "gform_5"
    var id = formEl.id || '';
    return /^gform_\d+$/.test(id);
  }

function getFormId(formEl) {
    if (!formEl) return null;
    var fid = (formEl.getAttribute && formEl.getAttribute('data-formid')) || '';
    if (fid) return String(fid);
    var id = formEl.id || '';
    var m = /gform_(\d+)/.exec(id);
    return m ? m[1] : null;
  }

function isAjaxForm(formEl) {
    if (!formEl) return false;
    try {
      var target = (formEl.getAttribute && formEl.getAttribute('target')) || '';
      if (target.indexOf('gform_ajax_frame_') === 0) return true;
      if (formEl.querySelector && formEl.querySelector('input[name="gform_ajax"]')) {
        return true;
      }
    } catch (e) {
      // DOM access failed — treat as non-AJAX; the reload path is the
      // safer default (it still only fires on confirmed success).
    }
    return false;
  }

function isNodeHidden(el) {
    try {
      if (el.hidden) return true;
      if (el.getAttribute && el.getAttribute('aria-hidden') === 'true') return true;
      var view = el.ownerDocument && el.ownerDocument.defaultView;
      if (view && view.getComputedStyle) {
        var cs = view.getComputedStyle(el);
        if (cs && (cs.display === 'none' || cs.visibility === 'hidden')) return true;
      }
    } catch (e) {
      // fall through
    }
    return false;
  }

function hasVisibleValidationErrors(rootEl) {
    if (!rootEl || !rootEl.querySelectorAll) return false;
    try {
      if (rootEl.className &&
          (' ' + rootEl.className + ' ').indexOf(' gform_validation_error ') !== -1) {
        return true;
      }
      var nodes = rootEl.querySelectorAll(
        '.gform_validation_errors, .validation_error, .gfield_error, .validation_message, [aria-invalid="true"]'
      );
      for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        if (isNodeHidden(node)) continue;
        if (node.getAttribute && node.getAttribute('aria-invalid') === 'true') return true;
        // Error classes and ARIA state are structural signals. Never read
        // rendered validation text: themes may include resolved field values.
        var classes = typeof node.className === 'string' ? node.className : '';
        if (/^(?:.*\s)?(?:gform_validation_errors|validation_error|gfield_error)(?:\s.*)?$/.test(classes)) return true;
      }
    } catch (e) {
      // fall through
    }
    return false;
  }

function safeFormId(formId) {
    if (formId == null) return null;
    var s = String(formId);
    return /^\d+$/.test(s) ? s : null;
  }

function hasServerRejectionMarkers(formId) {
    var fid = safeFormId(formId);
    try {
      if (fid) {
        var scope = document.querySelector('#gform_wrapper_' + fid) ||
          document.querySelector('#gform_' + fid + ', form[data-formid="' + fid + '"]');
        if (scope && scope.closest) {
          scope = scope.closest('.gform_wrapper') || scope;
        }
        // The submitted form isn't on this page at all → no rejection
        // evidence FOR THIS FORM, whatever other forms are showing.
        return scope ? hasVisibleValidationErrors(scope) : false;
      }
      var wrappers = document.querySelectorAll('.gform_wrapper');
      for (var i = 0; i < wrappers.length; i++) {
        if (hasVisibleValidationErrors(wrappers[i])) return true;
      }
    } catch (e) {
      // fall through
    }
    return false;
  }

function hasConfirmationMessage(formId) {
    var fid = safeFormId(formId);
    try {
      var nodes = document.querySelectorAll(
        '.gform_confirmation_message, [id^="gform_confirmation_message_"], [id^="gform_confirmation_wrapper_"]'
      );
      for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        if (isNodeHidden(node)) continue;
        // Presence of a visible, form-attributed confirmation element is a
        // structural legacy signal; its rendered contents are never inspected.
        if (!fid) continue;
        // Attribute the node to a form id if it carries one (own id or an
        // ancestor confirmation-wrapper id).
        var taggedId = null;
        var m = /gform_confirmation_(?:message|wrapper)_(\d+)/.exec(node.id || '');
        if (m) {
          taggedId = m[1];
        } else if (node.closest) {
          try {
            var anc = node.closest('[id^="gform_confirmation_wrapper_"], [id^="gform_confirmation_message_"]');
            var am = anc && /_(\d+)$/.exec(anc.id || '');
            if (am) taggedId = am[1];
          } catch (e2) {
            // .closest unavailable — treat as untagged
          }
        }
        if (taggedId === fid) return true;
      }
    } catch (e) {
      // fall through
    }
    return false;
  }
var pending={},complete={},TTL=120000,markerKey='__converly_gallery_gf_pending_v3';
var modernHookInstalled=false,seenEntries={};
window.dataLayer=window.dataLayer||[];
function forget(id){var entry=pending[id];if(entry&&entry.timer)clearTimeout(entry.timer);delete pending[id];}
function discardNotice(id,reason,form){try{document.dispatchEvent(new CustomEvent('converly:gform-attempt-discarded',{detail:{formId:String(id||''),reason:reason||'discarded',form:form||null}}));}catch(e){}}
function emitConfirmed(id,form,uniqueAccepted){id=safeFormId(id);if(!id||(!uniqueAccepted&&complete[id]))return;complete[id]=true;var handled=false;try{if(typeof window.__converlyGravityMethod2Emit==='function')handled=window.__converlyGravityMethod2Emit(id,form)===true;}catch(e){}if(!handled)window.dataLayer.push({event:'gravity_form_submitted',form_id:id});}
function fireLegacy(id){id=safeFormId(id);if(modernHookInstalled||!id||!pending[id]||complete[id])return;var form=pending[id].form;forget(id);emitConfirmed(id,form);}
function attempt(form,method,type){
 if(!isGravityForm(form))return;var id=safeFormId(getFormId(form));if(!id)return;
 if(modernHookInstalled){return;}
 if(type&&type!=='submit'){forget(id);discardNotice(id,'nonfinal');return;}
 forget(id);complete[id]=false;
 var entry={form:form,method:method||(isAjaxForm(form)?'iframe':'postback'),trusted:method==='postback',time:Date.now(),path:location.pathname,timer:null};
 entry.timer=setTimeout(function(){if(pending[id]===entry){forget(id);discardNotice(id,'timeout');}},TTL);pending[id]=entry;
}
function acceptedIframe(frame){
 if(modernHookInstalled||!frame||frame.tagName!=='IFRAME'||!/^gform_ajax_frame_\d+$/.test(frame.id||''))return;
 var id=frame.id.replace('gform_ajax_frame_','');if(!pending[id])return;
 try{var doc=frame.contentDocument;if(!doc||!doc.querySelector('.GF_AJAX_POSTBACK'))return;if(doc.querySelector('.gform_validation_error, .gform_validation_errors, .gfield_error, [aria-invalid=\"true\"]')){forget(id);discardNotice(id,'rejected');return;}var confirmation=doc.querySelector('#gform_confirmation_wrapper_'+id+', #gform_confirmation_message_'+id);if(confirmation&&!isNodeHidden(confirmation))fireLegacy(id);}catch(e){}
}
document.addEventListener('load',function(event){acceptedIframe(event.target);},true);
var jqueryHooked=false;
function hook(){
 if(!jqueryHooked&&typeof window.jQuery==='function'){jqueryHooked=true;window.jQuery(document).on('gform_confirmation_loaded.converlyGallery',function(event,id){fireLegacy(id);});}
 if(modernHookInstalled||!window.gform||!gform.utils||!gform.utils.addAsyncFilter)return;
 modernHookInstalled=true;
 gform.utils.addAsyncFilter('gform/submission/pre_submission',function(data){
  var form=data&&data.form;if(form&&!form.tagName&&form[0])form=form[0];var id=safeFormId(getFormId(form));
  if(!id)return data;
  if(data.submissionType!=='submit'){
   discardNotice(id,'nonfinal',form);
   return data;
  }
  if(data.abort===true)return data;
  if(data.submissionMethod==='postback'||data.submissionMethod==='iframe')data.submissionMethod='ajax';
  return data;
 });
 gform.utils.addAsyncFilter('gform/submission/submission_started',function(data){
  var form=data&&data.form;if(form&&!form.tagName&&form[0])form=form[0];var id=safeFormId(getFormId(form));
  if(id&&data.submissionType==='submit')complete[id]=false;
  return data;
 });
 gform.utils.addAsyncFilter('gform/ajax/post_ajax_submission',function(data){
  var form=data&&data.form;if(form&&!form.tagName&&form[0])form=form[0];var id=safeFormId(getFormId(form));if(!id)return data;
  var result=data&&data.submissionResult,verdict=result&&result.data;
  var rawEntryId=verdict&&verdict.entry_id,entryId=typeof rawEntryId==='number'?rawEntryId:(typeof rawEntryId==='string'&&/^\d+$/.test(rawEntryId)?Number(rawEntryId):NaN);
  var key=id+':'+entryId;
  if(result&&result.success===true&&verdict&&verdict.is_valid===true&&verdict.submission_type==='submit'&&isFinite(entryId)&&Math.floor(entryId)===entryId&&entryId>0&&entryId<=9007199254740991&&verdict.is_spam===false){
   if(seenEntries[key]){discardNotice(id,'duplicate-entry',form);return data;}
   seenEntries[key]=true;emitConfirmed(id,form,true);
  }else if(result&&result.success===true)discardNotice(id,'rejected',form);
  return data;
 });
 gform.utils.addAsyncFilter('gform/ajax/pre_display_error',function(data){
  if(data&&data.formId){var errorForm=null;try{errorForm=document.querySelector('#gform_'+safeFormId(data.formId));}catch(e){}discardNotice(data.formId,'ajax-error',errorForm);}
  return data;
 });
 document.addEventListener('gform/submission/submission_aborted',function(event){
  var form=event&&event.detail&&event.detail.form,id=safeFormId(getFormId(form));
  if(id)discardNotice(id,'abort',form);
 });
}
hook();document.addEventListener('gform/theme/scripts_loaded',hook);document.addEventListener('DOMContentLoaded',hook);window.addEventListener('load',hook);
document.addEventListener('submit',function(event){attempt(event.target,null,'submit');},true);
document.addEventListener('click',function(event){var el=event.target;if(!el||!el.closest)return;var control=el.closest('[id^="gform_submit_button_"]');if(control)attempt(control.closest('form'),null,'submit');},true);
function confirmationNode(node){if(modernHookInstalled||!node||node.nodeType!==1)return;var nodes=[];if(node.matches&&node.matches('[id^="gform_confirmation_message_"], [id^="gform_confirmation_wrapper_"]'))nodes.push(node);if(node.querySelectorAll){var list=node.querySelectorAll('[id^="gform_confirmation_message_"], [id^="gform_confirmation_wrapper_"]');for(var i=0;i<list.length;i++)nodes.push(list[i]);}for(var j=0;j<nodes.length;j++){var match=/gform_confirmation_(?:message|wrapper)_(\d+)/.exec(nodes[j].id||'');if(match&&!isNodeHidden(nodes[j]))fireLegacy(match[1]);}}
if(typeof MutationObserver==='function')new MutationObserver(function(mutations){for(var i=0;i<mutations.length;i++)for(var j=0;j<mutations[i].addedNodes.length;j++)confirmationNode(mutations[i].addedNodes[j]);}).observe(document.body||document.documentElement,{childList:true,subtree:true});
window.addEventListener('pagehide',function(){
 var markers=[];for(var id2 in pending)if(Object.prototype.hasOwnProperty.call(pending,id2)){var entry=pending[id2];if(entry.method!=='postback'||Date.now()-entry.time>10000||(!entry.trusted&&hasVisibleValidationErrors(entry.form)))continue;markers.push({id:id2,time:entry.time,path:entry.path});}
 if(markers.length)try{sessionStorage.setItem(markerKey,JSON.stringify(markers));}catch(e){}
});
function deferred(){if(modernHookInstalled)return;var markers;try{var raw=sessionStorage.getItem(markerKey);sessionStorage.removeItem(markerKey);markers=JSON.parse(raw||'[]');}catch(e){return;}if(!Array.isArray(markers))return;for(var i=0;i<markers.length;i++){var marker=markers[i],id=safeFormId(marker&&marker.id);if(!id||!marker.time||Date.now()-marker.time>60000)continue;if(hasServerRejectionMarkers(id))continue;if(hasConfirmationMessage(id)){pending[id]={};fireLegacy(id);}}}
if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',deferred);else deferred();

})();

Variable

Captures the ID of the form that was submitted, ready to reference in any tag. These are its exact settings.

Name

DLV - Gravity Form ID

Variable Type

Data Layer Variable

Data Layer Variable Name

form_id

Trigger

Fires when the 'gravity_form_submitted' event is received. Use it as the trigger for any conversion tag. These are its exact settings.

Name

CE - Gravity Forms Submitted

Trigger Type

Custom Event

Event Name

gravity_form_submitted

Download This Recipe

Get the ready-to-import file and upload it into Google Tag Manager. Everything shown above (the tag, the variable and the trigger) comes pre-built inside.

Built from Converly's own Gravity Forms detection code

Why It's the Best Recipe Out There

It is built from the same detection code we use in our own conversion tracking product, Converly, just adapted to run inside Google Tag Manager.

Only fires after Gravity Forms confirms the submission was accepted, so a visitor who fails validation (because they entered an invalid email address for instance) is never counted as a conversion.
Includes a backup detection path for sites where jQuery isn't available, a common theme conflict that silently breaks most Gravity Forms tracking scripts.
Tested on 13 October 2026 against real Gravity Forms forms, with AJAX on and off and with message and redirect confirmations. A genuine submission fires the event exactly once, a rejected submission fires nothing, and a double click still counts once.
Has been used to detect thousands of Gravity Forms submissions by our customers.

How to Use the Gravity Forms GTM Recipe

1

Install the Recipe

Download the recipe using the form above, then import it into your Google Tag Manager container. In GTM, head to Admin, choose Import Container, select the downloaded file, and pick the Merge option so it doesn't overwrite anything already in your container. The listener, variable and trigger are added for you automatically.

Importing the recipe container in Google Tag Manager
2

Configure Your Tags

Now that the recipe is installed, you can use it as a Trigger for your conversion tags. Here are two common examples.

Example 1: Google Analytics

Create a GA4 event tag and set the recipe's trigger (called CE - Gravity Forms Submitted) as its firing trigger. Every Gravity Forms submission now sends an event to Google Analytics.

A GA4 event tag using the recipe's trigger

Example 2: Google Ads

Add your Google Ads conversion tag and fire it on the recipe's trigger to report form fill conversions back to your campaigns.

A Google Ads conversion tag using the recipe's trigger

What This Enables You to Do (and What It Doesn't)

This recipe fires an event in Google Tag Manager whenever a successful Gravity Forms submission is detected. You can use that as a trigger to send conversions to Google Ads, Google Analytics and other tags.

What it does

Sends an Event to GTM

Detects successful Gravity Forms submissions and pushes an event called 'gravity_form_submitted' into your dataLayer automatically.

Tells You Which Form Fired

Captures the ID of the form that was submitted and passes it through with the 'gravity_form_submitted' event, so a site with several forms can fire different tags for different forms.

Creates a Trigger in GTM

Gives you a 'Trigger' in Google Tag Manager which you can use as the trigger for any of your conversion tags.

What it doesn't do

Send the conversion server-side

Everything fires client-side, so ad blockers can stop the tag loading and browser privacy restrictions can limit tracking to as little as a day.

No Click IDs or Identifiers

It does not capture the Google click ID, Facebook click ID, Meta pixel cookies, IP address or user agent, which ad platforms need for Enhanced Conversions (Google) or a proper Event Match Quality score (Meta).

No Personal Details

The script only fires an event. It does not capture the lead's name, email or phone number, all of which Google and Meta require for enhanced conversions and a high match score.

No Logging or Notifications

You can test it with Tag Assistant on install, but unless you check every week you have no way of knowing if it quietly breaks.

The Proper Way to Send Conversions to Google Ads, Meta Ads & More

This recipe is fine if you only send events to Google Analytics, which does not accept personal information or IP addresses. But to get a good Event Match Quality (EMQ) score in Meta, or use Enhanced Conversions in Google, you need to send the data server-side, together with the lead's name and email. That is what Converly does.

A Converly workflow sending Gravity Forms conversions to ad platforms

Here's why Converly is the best way to send conversions to Google Ads, Meta Ads, Microsoft Ads, LinkedIn Ads, etc.

Easy to set up

Converly gives you a simple drag-and-drop builder you can use to build a Conversion Flow. Simply select a trigger (like a Gravity Form being submitted) and then select your actions (like sending a conversion to Google Ads). No custom code, no complex configuration.

Sends Data Server-Side

Converly sends conversions directly from its servers to Google, Meta and the rest, instead of through the visitor's browser, so ad blockers and privacy restrictions can't get in the way.

Sends More Data

It captures the lead's name, email and phone plus the Google and Facebook click IDs, IP address and user agent, and sends them with every conversion. That enables Enhanced Conversions in Google Ads, or gives you an Event Match Quality (EMQ) score of 9 or 10 in Meta.

Full Conversion Log & Email Notifications

See every conversion, what was captured, what was sent to each platform and whether it was received. Get email alerts so tracking can't break without you knowing.

Supports Multiple Tools & Destinations

Detects submissions across 80+ form, scheduling and chat tools and sends to 20+ destinations including Google Ads, Meta, LinkedIn, Microsoft and TikTok. So if you ever add a new tool or start advertising on a new platform, it's just a few clicks.

Provides Free Support

Our team has 20 years of experience in conversion tracking and analytics and is here to help whenever you need it. With Google Tag Manager, you're on your own.

Start Your Free Trial

Start a 14-day free trial and track your conversions the proper way. No code, no complicated configuration.

About the author

Aaron Beashel
Aaron Beashel

Aaron is the founder of Converly. With over 15 years of experience in digital marketing and SaaS, he's passionate about helping businesses track and optimise their ad conversions.

Start your free trial

Easily send conversions to your ad platforms and analytics tools.
No code required.