This JavaScript code sets up a listener to track AJAX...

September 3, 2025 at 09:58 PM

<script id="gtm-jq-ajax-listen" type="text/javascript"> (function() { 'use strict'; var $; var n = 0; init(); function init(n) { // Ensure jQuery is available before anything if (typeof jQuery !== 'undefined') { // Define our $ shortcut locally $ = jQuery; bindToAjax(); // Check for up to 10 seconds } else if (n < 20) { n++; setTimeout(init, 500); } } function bindToAjax() { $(document).bind('ajaxComplete', function(evt, jqXhr, opts) { // Create a fake a element for magically simple URL parsing var fullUrl = document.createElement('a'); fullUrl.href = opts.url; // IE9+ strips the leading slash from a.pathname because who wants to get home on time Friday anyways var pathname = fullUrl.pathname[0] === '/' ? fullUrl.pathname : '/' + fullUrl.pathname; // Manually remove the leading question mark, if there is one var queryString = fullUrl.search[0] === '?' ? fullUrl.search.slice(1) : fullUrl.search; // Turn our params and headers into objects for easier reference var queryParameters = objMap(queryString, '&', '=', true); var headers = objMap(jqXhr.getAllResponseHeaders(), '\n', ':'); // Blindly push to the dataLayer because this fires within GTM dataLayer.push({ 'event': 'ajaxComplete', 'attributes': { // Return empty strings to prevent accidental inheritance of old data 'type': opts.type || '', 'url': fullUrl.href || '', 'queryParameters': queryParameters, 'pathname': pathname || '', 'hostname': fullUrl.hostname || '', 'protocol': fullUrl.protocol || '', 'fragment': fullUrl.hash || '', 'statusCode': jqXhr.status || '', 'statusText': jqXhr.statusText || '', 'headers': headers, 'timestamp': evt.timeStamp || '', 'contentType': opts.contentType || '', // Defer to jQuery's handling of the response 'response': (jqXhr.responseJSON || jqXhr.responseXML || jqXhr.responseText || '') } }); }); } function objMap(data, delim, spl, decode) { var obj = {}; // If one of our parameters is missing, return an empty object if (!data || !delim || !spl) { return {}; } var arr = data.split(delim); var i; if (arr) { for (i = 0; i < arr.length; i++) { // If the decode flag is present, URL decode the set var item = decode ? decodeURIComponent(arr[i]) : arr[i]; var pair = item.split(spl); var key = trim_(pair[0]); var value = trim_(pair[1]); if (key && value) { obj[key] = value; } } } return obj; } // Basic .trim() polyfill function trim_(str) { if (str) { return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); } } })(); </script>

This JavaScript code sets up a listener to track AJAX requests in a web page and pushes specific information about those AJAX requests into the dataLayer (commonly used with Google Tag Manager). Here's a breakdown of what this code does:


Key Functionality:

  1. Ensure jQuery is Loaded (init Function):

    • The code first checks if jQuery is available (typeof jQuery !== 'undefined') since it relies on jQuery for functionality.
    • If jQuery is not available, it re-checks for up to 10 seconds (n < 20) with retries every 500ms.
    • Once jQuery is loaded, it assigns the jQuery object to the local $ variable and calls the bindToAjax function.
  2. Listen for AJAX Events (bindToAjax Function):

    • The script sets up an event listener on ajaxComplete using $(document).bind('ajaxComplete', ...).
    • This listener is triggered every time an AJAX request completes.
  3. Parse and Extract Data:

    • When the ajaxComplete event is triggered, it:
      • Parses the AJAX request URL using a virtual <a> element to extract components like the pathname, hostname, protocol, query parameters, etc.
      • Converts query parameters and response headers into JavaScript objects using a utility function objMap.
  4. Push Information to the dataLayer:

    • The extracted data is structured into an object with detailed attributes about the AJAX request, including:
      • Request type (POST, GET, etc.)
      • URL components (e.g., pathname, hostname, queryParameters)
      • HTTP status codes and response status text
      • Timestamp of when the event occurred
      • Response content (if present).
    • The structured object is then pushed into the dataLayer array with an event key called 'ajaxComplete'.
  5. Utility Functions (objMap and trim_):

    • objMap: Converts delimited strings (like query strings or response headers) into JavaScript objects for easier handling.
    • trim_: A polyfill for trimming whitespace from strings in a cross-browser-compatible way.

Purpose and Usage:

  • General Purpose: This script is designed to monitor and track AJAX requests on a web page. It's typically used for analytics or tracking purposes (e.g., in conjunction with Google Tag Manager).

  • Integration with Tag Management: Pushing data to the dataLayer is common in Google Tag Manager (GTM). This allows marketers or developers to track user interactions and website events dynamically, without needing to hardcode tracking for every interaction.

Example Use Case:

  • Suppose a user triggers an AJAX-based form submission or API call on your website. This code ensures that the details of that AJAX request (e.g., URL, parameters, status, and response) are logged into the GTM dataLayer. Marketers can then use this data to define custom tags or events for performance tracking, user behavior analysis, or debugging.

Summary:

This script listens for AJAX request completions, extracts relevant information (like URL, query parameters, headers, response, etc.), and pushes that data into the dataLayer (which is essential for Google Tag Manager analytics). It provides granular visibility into background AJAX events occurring on the web page.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node