Why robust?
This AJAX listener is written in pure Javascript and acts as a middleman between your forms and the JavaScript APIs XMLHttpRequest
and Fetch
. This means that you don’t need to install any external library to make it work.
It listens to any AJAX request that your browser sends (not only requests from forms) so I recommend you to install this listener only on the pages you want to track AJAX requests from.
When an AJAX request is made, it sends the dataLayer event ajax_complete
only when a successful response is received from the server. This allows you to track only valid form submissions.
How to make it work?
First, you need to fill in the form below to get access to the full code to copy into a custom HTML tag in Google Tag Manager.
window.dataLayer = window.dataLayer || [];
var origin_open = XMLHttpRequest.prototype.open;
var origin_send = XMLHttpRequest.prototype.send;
var xhrRequestBody = "";
// Fill in the form below to get full code
Then, set up the trigger to make this tag fire only on the pages you need it to.
On every AJAX request, you should see the ajax_complete
event in the dataLayer.
What if it doesn’t work for you?
Even though this listener is robust in its conception, it may not work in your website environment.
If it’s the case, feel free to post a comment below this blog post and give all the details regarding your situation. I’ll be happy to help.