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.
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.
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();
});
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.
Now, let’s dive into some use cases we’ve put together to illustrate how Javascript API can solve common issues with Marketo Forms.
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];
}
}
})
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();
});
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!