How to Use the Javascript API for Marketo Forms

In this guide, we’ll show you how the Javascript API can be leveraged to improve the control and customization of your Marketo Forms.

Marketo Forms are a key component of effective marketing automation. By facilitating lead acquisition and streamlining the data collection process, they are pivotal for nurturing leads and driving conversions.

But Marketo Forms aren’t perfect. They are flexible in some ways, but inflexible in others.

With added control over your Marketo Forms through the Javascript API, you can stay compliant, enhance the user experience, execute background submissions, and much more.

What is the Javascript API?

For those who are new to the Javascript API, it is essentially a tool that enables communication between the user’s browser and your Marketo instance. And that last part is important to remember: Javascript does not run in Marketo. Instead, it runs in the user’s browser and sends information back to Marketo or brings information forward form Marketo.

If you want to learn more about the Javascript API, you can read the Marketo documentation here.

Benefits of Using Javascript API for Marketo Forms

We briefly teased these above, but the 3 main benefits of using the Javascript API for Marketo Forms are as follows:

1. Improved Form Customization

The Javascript API allows for extensive customization of form fields and behaviors, letting you tailor forms to meet specific compliance requirements or UI/UX design choices.

MktoForms2.whenReady(function(form) {
  form.onValidate(function() {
    var emailField = form.getValues().Email;
    if (!emailField.includes("@example.com")) {
      form.submittable(false);
      alert("Please use your company email address.");
    }
  });
});

 
2. Dynamic Modification of Form Fields

The Javascript API also allows form fields to change dynamically based on user inputs or other criteria (This aligns with the example we mentioned earlier regarding form field changes for USA and Canadian citizens).

MktoForms2.whenReady(function (form) {
  var countryField = form.getFormElem().find("select[name='Country']");
  var stateField = form.getFormElem().find(".stateField");
  var stateLabel = stateField.find("label");
  var stateSelect = stateField.find("select[name='State']");
 
  var usaStates = ["list of states"];
  var canadaProvinces = ["list of provinces"];


  countryField.change(function () {
    var selectedCountry = $(this).val();
    if (selectedCountry === "USA" || selectedCountry === "Canada") {
      stateField.show();
      if (selectedCountry === "Canada") {
        stateLabel.text("Province");
        stateSelect.empty();
        canadaProvinces.forEach(function (province) {
          stateSelect.append('');
        });
      } else {
        stateLabel.text("State");
        stateSelect.empty();
        usaStates.forEach(function (state) {
          stateSelect.append('');
        });
      }
    } else {
      stateField.hide();
    }
  });


  // Trigger the change event on load to handle pre-selected values
  countryField.change();
});

 
3. Programmatic Form Submissions

The Javascript API supports programmatic submissions, enabling background data collection and submission from third-party forms (some marketers use entirely different forms for unique styling options and features) to your Marketo form.

MktoForms2.loadForm("//app-ab00.marketo.com", "123-ABC-456", 789, function(form) {
  form.addHiddenFields({
    "hiddenField1": "value1",
    "hiddenField2": "value2"
  });
  form.submit();
});

 

Limitations of Using Javascript API for Marketo Forms

While the pros certainly outweigh the cons, there are a couple of limitations you should keep in mind when using the Javascript API for your Marketo Forms:

1. Implementation Complexity

Depending on your level of proficiency in Javascript and understanding of web development, setting up the API to work properly can be a challenge. There are a lot of moving parts and several things can go wrong.
For example, a common issue is when the API loads and runs on the web page before the form loads. When this happens, the API can’t find any field inputs and fails to capture data for your Marketo instance.

The reverse can happen as well (although it’s far more rare): The form loads fast on the webpage, allowing the user to fill out the form before the API has loaded to capture those field inputs.

2. Marketo’s Backend Infrastructure

Despite the API’s flexibility, it is still limited by Marketo’s backend rules. For example, Marketo requires all form fields to relate to a lead (their email address) with each submission being tied to a lead identifier.

pink line

Now, let’s dive into some use cases we’ve put together to illustrate how Javascript API can solve common issues with Marketo Forms.

Use Case 1: Language & Compliance Based on Country

Problem: There is a need to comply with different data protection regulations and provide localized experiences based on the user’s location.

Solution: The Javascript API can detect user location using the “Country” field or URL parameters, then dynamically adjust text and form fields accordingly. This results in a much better user experience, as well as assured compliance with differing international regulations.

Code Outline Example:

MktoForms2.whenRendered(function (form) {
  var opt = document.getElementById("Opt_In__c"); //opt-in element
  var check = opt.parentElement.parentElement.parentElement.parentElement; //checkbox element
  var text = document.getElementById("optin text").parentElement.parentElement.parentElement.parentElement; //text element in case there is no checkbox
  var uncheckedCountries = ["List of country codes that will display unchecked checkbox"]
  var precheckedCountries = ["List of country codes that will display prechecked checkbox"];
  var hideCountries = ["List of country codes that will hide the checkbox"];
  text.style.display = "none";
  check.style.display = "none";
  function unchecked() { //function that displays unchecked checkbox
    opt.checked = false;
    check.style.display = "block";
    text.style.display = "none";
  }
  function checked() { //function that displays prechecked checkbox
    opt.checked = true;
    check.style.display = "block";
    text.style.display = "none";
  }
  function hide() { //function that displays only the text
    opt.checked = true;
    check.style.display = "none";
    text.style.display = "block";
  }
  var select = document.getElementById("CountryCode");
    select.addEventListener("change", (e) => {
      if (hideCountries.includes(select.value)) {
        hide();
      } else if (uncheckedCountries.includes(select.value)) {
        unchecked();
      } else if (precheckedCountries.includes(select.value)) {
        checked();
      }
    });
})
MktoForms2.whenRendered(function (form) {
  var translations = {
    "en": {
      "FirstName": "First Name:",
      "LastName": "Last Name:",
      "Email": "Email Address:"
    },
    "pt": {
      "FirstName": "Nome:",
      "LastName": "Sobrenome:",
      "Email": "Endereço de Email:"
    }
  }
  // You can get the language from the country code as specified bellow and change the language of the form whe the county field changes
  var countryLanguage = {
    "US": "en",
    "UK": "en",
    "BR": "pt",
    "PT": "pt",
  }
  var language=countryLanguage
  var select = document.getElementById("CountryCode");
    select.addEventListener("change", (e) => {
      for (var labelTranslation in translations[language]) {
        // Identify each label element and change its text if it exists
        var labelElement = document.querySelector("label[for='" + labelTranslation + "']");
        if (labelElement) {
          labelElement.textContent = translations[language][labelTranslation];
        }
      }
    })
  // You could also get the language from a token (remember to define it in you program) and immediatly change the language of the form as below
  var language = "{{ my.language }}"
  for (var labelTranslation in translations[language]) {
    // Identify each label element and change its text if it exists
    var labelElement = document.querySelector("label[for='" + labelTranslation + "']");
    if (labelElement) {
      labelElement.textContent = translations[language][labelTranslation];
    }
  }
})

 

Use Case 2: Hidden Form Submission

Problem: There is a situation where a form submission needs to occur without any user interaction. This could be event tracking or other automated processes for data collection.

Solution: You can set up hidden form fields and trigger form submissions using the Javascript API. This allows data to be seamlessly collected from the background and then sent to your Marketo instance. Overall, this enables far more flexibility when it comes to data collection and submission processes.

Code Outline Example:

HTML

<form id="mktoForm_2095" style="display: none"></form>
<script>
MktoForms2.loadForm("//YOUR-DOMAIN", "YOUR MUNCHKIN", 123456); // You can get this in the embed code;
</script>

 
Javascript

document.getElementById('YOUR-FORM-ID').addEventListener('submit', function(event) {
  // Prevent page to redirect
  event.preventDefault();
  // Get URL Params
  var url = new URL(window.location.href);
  var utmsource = url.searchParams.get("utm_source")
  var utmmedium = url.searchParams.get("utm_medium")
  var utmcampaign = url.searchParams.get("utm_campaign")


  // Get Form Values
  var firstName = document.getElementById("FIRST-NAME-ID").value;
  var lastName = document.getElementById("LAST-NAME-ID").value;
  var email = document.getElementById("EMAIL-ID").value;


  var myForm = MktoForms2.getForm(123456); // Replace by your Marketo form ID
 
  var hiddenFields={
    "Email": email,
    "FirstName": firstName,
    "LastName": lastName,
    "Most_Recent_UTMSource":utmsource,
    "Most_Recent_UTM_Medium":utmmedium,
    "Most_Recent_UTM_Campaign":utmcampaign,
  }
  // Add hidden fields to the hidden form
  myForm.addHiddenFields(hiddenFields);
  // Submit the hidden form
  myForm.submit();
  // Submit the regular form
  document.getElementById('YOUR-FORM-ID').submit();
});

 
pink line

Leveraging the Javascript API for Marketo Forms opens up a world of possibilities for improved customization and dynamic interaction.

As a marketer, it’s an important tool that’ll allow you to enhance user experience, ensure compliance, and streamline data collection processes – which will ultimately drive more effective lead acquisition and conversion strategies.

And while there are some limitations to consider, the benefits definitely outweigh them.

As we covered above, proper implementation of the API can be complex.

So if you need any help at all, reach out to us here!

How to Align Sales and Marketing

TLDR: Aligning sales and marketing teams is critical to achieving a better balance of lead quality and quantity. By fostering collaboration, creating shared definitions and workflows, and analyzing first-party data, sales and marketing can work together towards common goals and make data-driven decisions. By taking these steps, organizations can improve collaboration, work with a clearer sense of purpose, and ultimately win and keep more business.

pink line

Sales and marketing want the same thing: Great leads that quickly turn into revenue.

Achieving the right balance of quality and quantity is a continual challenge. Even with a perfect ICP and stellar demand funnel, prospects ditch demos, opportunities fail to close, and customers churn.

What often happens when KPIs are missed? We typically see finger-pointing, defensive postures, blame games, knee-jerk reactions, and other behaviors that simply don’t benefit the organization.

Instead of declaring your teammate is underperforming, look at the data and the levers available to pull. Conjecture is not a reliable strategy for creating revenue. Double down on data and alignment to avoid the perils of blame and divisiveness.

 

“Conjecture is not a reliable strategy for creating revenue.”

 

If friction and missed KPIs are common in your company, this Tough Talks Made Easy is for you. You’ll learn how to get your demand gen back on track by fostering better sales and marketing alignment and implementing a strategy driven by meaningful data analysis.

 

Coming together

When sales and marketing work in siloes, internal dysfunction creates disjointed customer experiences. Sales can’t close the most suitable business for the company if marketing’s campaigns don’t resonate with the needs of these audiences. Likewise, marketing’s efforts to attract the best leads won’t fuel growth if sales’ outreach lacks personalization.

The North Stars of value and revenue should bring sales and marketing together to collaborate on strategy and goals.

Create shared definitions and workflows

First, both teams need shared definitions of common terms. For instance: what specifically qualifies a lead as an MQL, SAL, or SQL? Sales and marketing should also create an agreed-upon methodology for lead scoring, which involves investigating a few data points.

Based on the kinds of customers you successfully do business with, what budget, authority, and demographic traits suggest that a prospect is highly matched to your company? From past closed business, what behaviors at different stages in the buying cycle suggest they’re ready for sales to pursue?

Both sales and marketing have valuable perspectives and reports to share with each other.

Sales, for example, can tell marketing more about why opportunities have been won or lost, what prospects have felt or wanted, and why past MQLs haven’t matched their needs. And marketing can advise sales on the content types that are likely to appeal to the priority leads they’re targeting.

Share workflows and communication structures

Sales and marketing leaders can incentivize a cultural shift towards alignment by creating shared workflows and communication structures. Establishing SLAs together, for instance, makes sure that both teams understand each others’ accountabilities and the exact work that makes a lead progress through the revenue cycle.

 

“Lead with data-driven decision-making.”

 

Leaders of both teams should create shared KPIs and encourage a clear understanding of how sales and marketing’s individual KPIs contribute towards achieving overarching goals.

Taking these steps contributes to a higher quality of collaboration and understanding between sales and marketing.

At the heart of every good strategy, however, is knowledge of why your campaigns or outreach efforts are valuable to the people you’re targeting—because if that value is limited or unclear, the people you’re targeting may not match well with your business, and are unlikely to be sources of revenue.

To help with this, sales and marketing leaders must lead the way with better data-driven decision-making.

 

Finding trend lines

When sales and marketing leaders meet quarterly, they often bring data points to the table like:

📊business closed in the quarter
📊pipeline for the months ahead, and
📊lead volume.

Dig into first-party data

Less frequently do they dig into their first-party data from a forensic perspective, allowing anecdotal observations about customer trends to guide strategy. This is a significant reason why lead-gen efforts fall flat.

To determine who your ideal customers are, leadership should instead look at the data on your total addressable market for months and years past. Are prospects of particular company sizes, verticals, regions, or job titles more prone to churn or dropping off the funnel than others? Where in the funnel do they go?

From this analysis, you can answer questions such as:

✋Is your lead qualification criteria sufficient?
✋Are your target customer types and markets optimal for your business goals?
✋Do your sales and marketing teams need more training to reach higher-value customers?

Identify demographic and firmographic trends

Identify the demographic and firmographic trends within metrics like closed/lost rates, closed/won, open opportunities, and sales-accepted leads. By doing so, you can make a confident hypothesis about the customer types that are most valuable, sustainable, and receptive to your business.

 

“Steer decision-making away from hunches and towards clear evidence.”

 

This outcome justifies contracting the support of a data scientist to parse through your systems and establish the trend lines, but if your budget’s tight, marketing can lead the way. Even just pulling closed/won rates from your CRM, you can begin to steer decision-making away from hunches and towards clear evidence.

Once you’ve identified the prospect types to pursue as priorities, both sales and marketing should research and share insights on these prospects.

🔍What are the emerging and relevant trends in their industries?
🔍What concerns are likely to motivate them at their level of seniority, region, or company?

From this, you’ll get a greater sense of how to approach your target audience and what you can offer that truly speaks to their needs. This understanding should steer the direction of both marketing’s campaigns and sales’ outreach.

 

The result

When sales and marketing leaders invest in aligning their teams, everyone wins.

Creating communication structures for sales and marketing to share goals, set strategies, and refine approaches together based on first-party data analysis substantially improves how you work.

It leads people to work with a clearer sense of purpose, more effective collaboration, and more confident decision-making—all of which are conducive to winning and keeping business.

Do you need help to better align sales and marketing? Get in touch today!