Marketo Javascript Forms API

LucasMachado
Level 3 - Champion Level 3 - Champion
Level 3 - Champion

What Is the Marketo Engage Forms JavaScript API?

 

The Marketo Engage Forms JavaScript API is a framework that allows developers to manipulate and customize forms beyond the default options available in the Marketo Engage interface. Using JavaScript, you can interact with form elements, control form behavior, and create a personalized user experience.

 

As a Marketo Engage trailblazer in Brazil, I’m used to working with global clients. While developing new campaigns, I face different challenges related to the global need of them, such as compliance management and language preferences, and the Marketo Forms API has proven to be very useful in those cases, which I’ll showcase below. I also presented on that topic on the Digital Skill Exchange, and you can find the recording below:

 

Key Features:

  • Dynamic Form Customization: Modify form fields, labels, and behavior based on user interactions or external data.
  • Enhanced User Experience: Add interactivity, such as conditional logic or dynamic pre-filling.

 

Embedding a Form

Start by creating your form in Marketo Engage. Once created, you can embed it on any web page by adding the following script to the HTML of your page:

 

 

<script src="//app-sjst.marketo.com/js/forms2/js/forms2.min.js"></script>

<form id="mktoForm_YourFormID"></form>

<script>

    MktoForms2.loadForm("//app-sjst.marketo.com", "YourMunchkinID", YourFormID);

</script>

 

 

Replace YourFormID and YourMunchkinID with your specific Marketo Engage instance identifiers. The loadForm method initializes the form on your web page. You can also find this code by going to your specific form in Marketo Engage and clicking on “embed code”.

 

API Methods

 

This API has many different methods that you can use to communicate to objects (see the full list here), some of the most useful to me are:

  • addHiddenFields: Allows you to add and populate fields programmatically without the user seeing it.
  • onValidate: When the form is being validated for submission you can trigger a specific set of actions.
  • submit: Submit the form programmatically.
  • setValues: Set the values of fields in the form programmatically (it can be used for progressive profiling for example.)

 

Use Cases

 

Hidden form submission

It’s common to find situations where a website uses a non-Marketo Engage form solution—often as a result of a website redesign where Marketo Engage forms were overlooked during migration. In these cases, marketers may still need to track event data or collect leads into Marketo Engage without re-creating the whole website to add Marketo Engage forms.

 

In this case, marketers can use the Marketo Engage JavaScript API to set up hidden form fields and automate submissions in the background. This method enables you to collect data from non-Marketo Engage form solutions, seamlessly sending the data to your Marketo Engage instance.

 

 

document.getElementById(‘YourFormID’).addEventListener('submit', function(event) {

    event.preventDefault(); 

    const hiddenFields = {

        "Email": document.getElementById("EmailFieldID").value,

        "FirstName": document.getElementById("FirstNameFieldID").value,

        "LastName": document.getElementById("LastNameFieldID").value

    };



    MktoForms2.getForm(YourMktoFormID).addHiddenFields(hiddenFields).submit();

    event.target.submit();

});

 

 

Automatic Localization

 

Instead of having one form for each language, you could have only one form that dynamically changes the language according to the user country. The JavaScript API enables you to detect a user’s location through the “Country” field or URL parameters and dynamically adjust form text and fields. This creates a localized experience, ensuring users see content in their preferred language and format. You can also use the same logic to ensure compliance with local regulations.

 

 

MktoForms2.whenRendered(function (form) {

  const translations = {

    en: {

      FirstName: "First Name:",

      LastName: "Last Name:",

      Email: "Email Address:",

    },

    es: {

      FirstName: "Nombre:",

      LastName: "Apellido:",

      Email: "Correo Electrónico:",

    },

  };



  const countryLanguage = {

    US: "en",

    UK: "en",

    MX: "es",

    ES: "es",

  };



  // Function to update form labels based on language

  function updateFormLabels(language) {

    Object.keys(translations[language] || {}).forEach((field) => {

      const labelElement = document.querySelector(`label[for='${field}']`);

      if (labelElement) {

        labelElement.textContent = translations[language][field];

      }

    });

  }



  // Update labels when the country changes

  const countrySelect = document.getElementById("CountryCode");

  countrySelect.addEventListener("change", (e) => {

    const selectedCountry = e.target.value;

    const language = countryLanguage[selectedCountry] || "en"; // Default to English

    updateFormLabels(language);

  });



  // Update labels immediately based on a token-defined language

  const languageFromToken = "{{ my.language }}";

  updateFormLabels(languageFromToken || "en");

});

 

 

Web Analytics Integration via Tag Management Systems

 

You can also use the Javascript API to integrate your form submissions with Web Analytics platforms through Tag Management Systems, such as Google Tag Manager. This will help your business understand better user behavior and measure the effectiveness of your pages by enriching your web analytics tool. To achieve that, you can use the Marketo Engage Javascript API to trigger a custom event when the form is submitted, which will push the custom event to the Web Analytics data layer. Below is a sample code to integrate with GA4 via GTM.

 

 

form.onSuccess(function(values, followUpUrl) {

    // Push form submission data to GA4

    dataLayer.push({

        event: 'formSubmission',

        formId: form.getId(), // Marketo form ID

        formName: 'Contact Us Form', // Example: Customize form name

        formFields: {

            email: values.Email, // Example field

            firstName: values.FirstName, // Example field

            lastName: values.LastName // Example field

        }

    });

    return true;

});

 

Next steps
To begin with the Marketo Engage Forms JavaScript API, I’d recommend taking the following actions:

 

  1. Review your form strategy and experience.
  2. Copy from the sample Form API codes in this article to implement the use cases.
  3. Navigate to your Marketo Engage form and obtain the code by going into Form Actions > Embed Code and implement it on your Marketo Engage landing pages or web pages.


Questions? Comment below or ask my GPT trained on the forms API.

 

105
0