How to Capture UTM Parameters and Pass Them Into JotForm

Man using computer at coffee shop

Capturing UTM parameters (such as utm_source, utm_medium, utm_campaign, etc.) is crucial for tracking the performance of marketing campaigns. You want to capture these UTM parameters on your site and pass them into forms, such as JotForm, but natively, Jotform (and some other form builders) doesn’t have a solution for this

In this tutorial, we’ll guide you step-by-step on how to capture UTM parameters from the URL, store them in local storage and cookies, and then pass them into a JotForm.

Prerequisites

  • Access to Cpanel
  • A form with hidden fields for capturing UTM parameters
  • Editing access to your website

Step 1: Capture UTM Parameters and Store Them in Cookies and Local Storage

The first step is to capture the UTM parameters from the URL and store them in cookies. We’ll use create a custom script and store it in our theme’s asset folder

  1. Open Cpanel and Locate Your Website’s Theme Folder
  2. Create a file at the the location: themeFolder/assets/js/ and name the file tracking.js
  3. Paste the following code in your tracking.js file:
(function() {
    console.log("Code is running");

    // Helper functions
    function getURLParam(name) {
        var urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    }

    function getCookie(name) {
        var cookies = document.cookie.split('; ');
        for (var i = 0; i < cookies.length; i++) {
            var parts = cookies[i].split('=');
            if (parts[0] === name) {
                return decodeURIComponent(parts[1]);
            }
        }
        return null;
    }

    function setCookie(name, value, days) {
        var d = new Date();
        d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        document.cookie = name + "=" + encodeURIComponent(value) + ";" + expires + "; path=/";
    }

    function setStorage(name, value) {
        try {
            sessionStorage.setItem(name, value);  // Session-based storage
            localStorage.setItem(name, value);   // Persistent storage
            setCookie(name, value, 7);           // Fallback for cross-tab tracking
        } catch (e) {
            console.warn("Storage access denied for:", name);
        }
    }

    function getStorage(name) {
        return sessionStorage.getItem(name) || localStorage.getItem(name) || getCookie(name);
    }

    // Capture UTM parameters & store them
    var utmParams = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content"];
    for (var i = 0; i < utmParams.length; i++) {
        var param = utmParams[i];
        var value = getURLParam(param);
        if (value) setStorage(param, value);
    }

    // Capture first landing page only if not already set
    if (!getStorage("landing_page")) {
        var landingPage = window.location.href.replace(/\?/g, "_");
        setStorage("landing_page", landingPage);
    }

    // Capture referrer only if it’s not set and not from the same domain
    var referrer = document.referrer;
    if (referrer && !getStorage("referrer")) {
        var currentDomain = window.location.hostname;
        var referrerDomain = new URL(referrer).hostname;
        
        if (referrerDomain !== currentDomain) {
            setStorage("referrer", referrer);
        }
    }

    // Debugging: Log stored values
    console.log("Stored UTM & tracking data:", {
        utm_source: getStorage("utm_source"),
        utm_medium: getStorage("utm_medium"),
        utm_campaign: getStorage("utm_campaign"),
        utm_term: getStorage("utm_term"),
        utm_content: getStorage("utm_content"),
        landing_page: getStorage("landing_page"),
        referrer: getStorage("referrer")
    });

})();

Step 2: Call Your tracking.js Script in functions.php File

Add the following to your functions.php file located within your theme folder within the php tags.

/**
 * Enqueue Tracking Script Properly
 */
function enqueue_tracking_script() {
    wp_enqueue_script( 'tracking-script', get_stylesheet_directory_uri() . '/assets/js/tracking.js', array(), null, true ); // Load in footer
}
add_action( 'wp_enqueue_scripts', 'enqueue_tracking_script' );

Step 3: Pass UTM Parameters to JotForm

Now that the UTM parameters are stored in cookies, we need to pass them into hidden fields in your JotForm form. Open Jotform and create a short text and name it appropriately. I created 5 fields: utm_source, utm_medium, utm_campaign, utm_term, and utm_content. Go into the advanced section on that field and locate “Unique Name.” Personally, I renamed all the fields to have unique names to fit the parameter (utm_source: source, utm_content: content, etc), but you can do what you want. Do note that if you name them something else, you will need to change some code later.

Short text properties menu on Jotform

Step 4: Test That Your Storing The UTM Parameters

Go to your website, and add this to the end of the url: ?utm_source=testSource&utm_content=testContent

Open developer tools or inspect on your website and go to console to check that the code is loading. It should look something like this:

Step 5: Inject the Parameters into your Form

If everything looks good up to this point, you can add the code that will actually inject those parameters into the form. On the page where your form is hosted, add this code (but swap out {formID} with your form ID). If you’re having issues locating your form ID, go to edit the form and it’s the number right after https://www.jotform.com/build/

<script>
(function() {
  // Function to get value from sessionStorage, localStorage, or cookies (in that order)
  function getStoredValue(name) {
    try {
      return sessionStorage.getItem(name) || 
             localStorage.getItem(name) || 
             getCookie(name) || null;
    } catch (e) {
      console.warn("Storage access denied for:", name);
      return null;
    }
  }

  // Function to retrieve a cookie value
  function getCookie(name) {
    var cookies = document.cookie.split('; ');
    for (var i = 0; i < cookies.length; i++) {
      var parts = cookies[i].split('=');
      if (parts[0] === name) {
        return decodeURIComponent(parts[1]);
      }
    }
    return null;
  }

  // Retrieve stored values (UTM & tracking data)
  var utmSource = getStoredValue("utm_source") || "";
  var utmCampaign = getStoredValue("utm_campaign") || "";
  var utmMedium = getStoredValue("utm_medium") || "";
  var utmTerm = getStoredValue("utm_term") || "";
  var utmContent = getStoredValue("utm_content") || "";
  var landing_page = getStoredValue("landing_page") || "";
  var referrer = getStoredValue("referrer") || "";

  // Function to safely build the URL (avoids empty values breaking the URL)
  function buildQueryParams(params) {
    return Object.entries(params)
      .filter(([_, value]) => value) // Remove empty values
      .map(([key, value]) => encodeURIComponent(key) + "=" + encodeURIComponent(value))
      .join("&");
  }

  // Construct the JotForm URL dynamically
  var jotFormBaseURL = "https://form.jotform.com/jsform/{formID}";
  var queryParams = buildQueryParams({
    source: utmSource,
    medium: utmMedium,
    campaign: utmCampaign,
    content: utmContent,
    term: utmTerm,
    landing_page: landing_page,
    referrer: referrer
  });

  var jotFormLink = document.createElement("script");
  jotFormLink.src = jotFormBaseURL + (queryParams ? "?" + queryParams : ""); // Append query params if available
  document.head.appendChild(jotFormLink);

  // Debugging: Log stored values
  console.log("JotForm script loaded with parameters:", queryParams);

})();
</script>

Looking to move soon?

Check out UniMovers and save 30-50% on your move as compared with traditional moving!

Troubleshooting Tips

  • No Cookies Set: If the cookies aren’t being set, double-check the script that captures the UTM parameters. Ensure that the getUrlParameter() function is correctly reading the URL and that the cookies are being set with the correct path.
  • Form Fields Not Populated: If the form fields aren’t being populated, inspect the field names in JotForm and ensure they match the names used in the JavaScript (e.g., utm_source, utm_medium, utm_campaign).

Conclusion

Capturing and passing UTM parameters into a JotForm is a great way to enhance your marketing analytics and track the performance of your campaigns. By using Local Storage and Cookies to store UTM parameters in cookies and then passing them into JotForm, you ensure that all relevant data is captured when users submit their forms.

With these steps, you’ll have a robust setup that automates UTM tracking and helps you gain deeper insights into how visitors interact with your forms based on marketing campaigns. Oh, and P.S., if you want to watch the video on how I did this, it’s right here.

Website |  + posts

Collin Flynn comes born and raised in Racine, Wisconsin off the coast of Lake Michigan. He graduated from Coe College in 2019 with a degree in physics. He is the founder of College Movers, a company that enables young entrepreneurial-minded people to open their own business utilizing the gig-economy and its technological backing. Collin has 4+ years of experience in the moving industry and writes about moving, fitness, and business. When he's not managing his business you can find him running, biking, or swimming — after all he does have triathlons to train for.