Tracking Ajax Events via GTM
Ajax forms are notoriously hard to track using built in GTM Click triggers, though if your site relies on jQuery for sending Ajax requests they don’t have to be.
The problem lies in how form events are handled. In the ye olde days of the internet, back in the early 2000’s, forms submitted by navigating to a new page and passing data to the server. Modern web applications intercept the form submit event, cancelling its propagation through the DOM (and if you don’t know what the DOM is, it pretty much means HTML to an advertiser), and preventing the page refresh. When the event is intercepted, the data is pulled from the form and sent via our arch nemesis, Ajax!
The difficulty tracking ajax events actually has nothing to do with ajax. It’s actually a side effect of canceling the event propagation through the DOM. GTM will register an event listener for it’s click trigger, though if the form listener receives the event first then it cancels event propagation and your trigger never hears about the click.
What to do we do now?
Well, we really aren’t concerned with when the element was clicked, but with when the form, or other ajax event, actually succeeded. So what we really want is a way to listen to ajax events on the page without having to compete with the website’s event handlers.
Here’s a tag that can do exactly that!
What's going on here?
This tag receives every successful ajax request on the page after it has returned and then pushes the data into the GTM data layer. Now that we have access to this data all thats left to do is create a handful of data layer variables and we can start building GTM triggers and tags!
Here some data layer variables you may want to consider using ..
These variables can be used in combination to create triggers for specific ajax successful requests. For example ..
Hopefully this will help you to stop fighting for events with those pesky ajax forms and focus more on what to track, and not how to track. If you have any troubles with the script let me know in the comments and I'll do my best to help you through the process. : )