Advertisement
prabapro

GTM Ajax Listener

Nov 17th, 2022 (edited)
612
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <script id="gtm-jq-ajax-listen" type="text/javascript">
  2.   (function() {
  3.     'use strict';
  4.     var $;
  5.     var n = 0;
  6.     init();
  7.  
  8.     function init(n) {
  9.       // Ensure jQuery is available before anything
  10.       if (typeof jQuery !== 'undefined') {
  11.         // Define our $ shortcut locally
  12.         $ = jQuery;
  13.         bindToAjax();
  14.         // Check for up to 10 seconds
  15.       } else if (n < 20) {
  16.         n++;
  17.         setTimeout(init, 500);
  18.       }
  19.     }
  20.  
  21.     function bindToAjax() {
  22.       $(document).bind('ajaxComplete', function(evt, jqXhr, opts) {
  23.         // Create a fake a element for magically simple URL parsing
  24.         var fullUrl = document.createElement('a');
  25.         fullUrl.href = opts.url;
  26.         // IE9+ strips the leading slash from a.pathname because who wants to get home on time Friday anyways
  27.         var pathname = fullUrl.pathname[0] === '/' ? fullUrl.pathname : '/' + fullUrl.pathname;
  28.         // Manually remove the leading question mark, if there is one
  29.         var queryString = fullUrl.search[0] === '?' ? fullUrl.search.slice(1) : fullUrl.search;
  30.         // Turn our params and headers into objects for easier reference
  31.         var queryParameters = objMap(queryString, '&', '=', true);
  32.         var headers = objMap(jqXhr.getAllResponseHeaders(), '\n', ':');
  33.        
  34.         // [Added by Praba from MeasureSchool] Get form inputs & push it to data layer
  35.         var inputs = document.querySelectorAll('input');
  36.         var formInputs = {};
  37.         for (var i = 0; i < inputs.length; i++) {
  38.           formInputs[inputs[i].id] = inputs[i].value;
  39.         }
  40.        
  41.         // Blindly push to the dataLayer because this fires within GTM
  42.         dataLayer.push({
  43.           event: 'ajaxComplete',
  44.           attributes: {
  45.             // Return empty strings to prevent accidental inheritance of old data
  46.             type: opts.type || '',
  47.             url: fullUrl.href || '',
  48.             queryParameters: queryParameters,
  49.             pathname: pathname || '',
  50.             hostname: fullUrl.hostname || '',
  51.             protocol: fullUrl.protocol || '',
  52.             fragment: fullUrl.hash || '',
  53.             statusCode: jqXhr.status || '',
  54.             statusText: jqXhr.statusText || '',
  55.             headers: headers,
  56.             timestamp: evt.timeStamp || '',
  57.             contentType: opts.contentType || '',
  58.             // Defer to jQuery's handling of the response
  59.             response: jqXhr.responseJSON || jqXhr.responseXML || jqXhr.responseText || '',
  60.             formInputs: formInputs
  61.           },
  62.         });
  63.       });
  64.     }
  65.  
  66.     function objMap(data, delim, spl, decode) {
  67.       var obj = {};
  68.       // If one of our parameters is missing, return an empty object
  69.       if (!data || !delim || !spl) {
  70.         return {};
  71.       }
  72.       var arr = data.split(delim);
  73.       var i;
  74.       if (arr) {
  75.         for (i = 0; i < arr.length; i++) {
  76.           // If the decode flag is present, URL decode the set
  77.           var item = decode ? decodeURIComponent(arr[i]) : arr[i];
  78.           var pair = item.split(spl);
  79.           var key = trim_(pair[0]);
  80.           var value = trim_(pair[1]);
  81.           if (key && value) {
  82.             obj[key] = value;
  83.           }
  84.         }
  85.       }
  86.       return obj;
  87.     }
  88.     // Basic .trim() polyfill
  89.     function trim_(str) {
  90.       if (str) {
  91.         return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  92.       }
  93.     }
  94.   })();
  95.   /*
  96.    * v0.1.0
  97.    * Created by the Google Analytics consultants at http://www.lunametrics.com
  98.    * Written by @notdanwilkerson
  99.    * Documentation: http://www.lunametrics.com/blog/2015/08/27/ajax-event-listener-google-tag-manager/
  100.    * Licensed under the Creative Commons 4.0 Attribution Public License
  101.    */
  102. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement