How to track forms
Manual Contact Form Tracking
AllIt may be handy to maintain common structure for contact form events through multiple places (eg. on multiple microsites created by different developer teams, for randomly generated input names without common semantics).
Having a consistent structure will help analysts and will quicken the formsnext steps of working with the collected data.
When using Manual Contact Form Tracking it is important to remember about disabling automatic form tracking that could have been already set on the sitewebsite. shouldIn this way, events will not be trackedreceived viamultiple times.
To do it please choose one from the callingfollowing.
- Remove
MeiroEvents.track("formSubmit")
;insidefrom initialization script in the page header. - Alternatively, prevent event so it doesn’t occur on
documentElement
level and implement the following MeiroEvents method call:
if (MeiroEvents && typeof MeiroEvents.track === "function") {
MeiroEvents.track("contactFormSubmit", {
form_id: "contact_form",
email: "john@doe.com",
first_name: "John",
last_name: "Doe",
phone_number: "00420604334554",
national_id: "CZ",
gender: "male",
birthdate: "10-10-1934",
whatsapp: "@strictacular",
instagram: "spectator",
facebook: "JohnDoe1943",
linkedin: "JohnDoe-49456780",
internal_user_id: "09FDAS0930",
external_id: "094309F09SD09",
field00: true,
...
field30: ["car", "bicycle"]
})
}
You are free to add .then()
or .catch()
functions as track function return javascript Promise.
Validation
The event payload must pass strict Meiro Events initializingSDK scriptvalidation, locatedotherwise, it will be rejected.
The rules are the following:
form_id: ["required", "string", "minLength1"],
email: ["string", "optional"],
first_name: ["string", "optional"],
last_name: ["string", "optional"],
phone_number: ["string", "optional"],
national_id: ["string", "optional"],
gender: ["string", "optional"],
birthdate: ["string", "optional"],
whatsapp: ["string", "optional"],
instagram: ["string", "optional"],
facebook: ["string", "optional"],
linkedin: ["string", "optional"],
internal_user_id: ["string", "optional"],
external_id: ["string", "optional"],
field00: optional scalar value (null, string, number, boolean) or array of scalar values,
...
field30: optional scalar value (null, string, number, boolean) or array of scalar values
The event will be rejected if you send it with payload:
- Without filled string
form_id
. - With field violating validation rule (eg. gender with number value).
- With additional unknown fields.
If you are not able to send the event successfully, add .catch()
function to check the validation error.
MeiroEvents.track("contactFormSubmit", {
email: "john@doe.com",
first_name: "John",
last_name: "Doe",
phone_number: "00420604334554",
national_id: "CZ",
gender: "male",
birthdate: "10-10-1934,
whatsapp: "@strictacular",
instagram: "spectator",
facebook: "JohnDoe1943",
linkedin: "JohnDoe-49456780",
internal_user_id: "09FDAS0930",
external_id: "094309F09SD09"
}).catch(err => {
console.log(err.name); // ValidationError
console.log(err.message); // The field form_id must be present in theevent sitepayload.
header. })
Full Code Vanilla JS example
Please contactConsider the Meirofollowing team,form to submit asynchronously:
<form id="contact-form">
<div class="form-row">
<label for="name">Name:</label>
<input name="name" type="text" required />
</div>
<div class="form-row">
<div><label for="gender">Gender:</label></div>
<input type="radio" name="gender" value="male" checked /> Male<br />
<input type="radio" name="gender" value="female" /> Female<br />
<input type="radio" name="gender" value="other" /> Other
</div>
<div class="form-row">
<div><label>Vehicles:</label></div>
<input type="checkbox" name="vehicle1" value="Bike" /> I have a bike<br />
<input type="checkbox" name="vehicle2" value="Car" /> I have a car
</div>
<button type="submit">Submit</button>
</form>
Then the javascript code can be following (placed inside the bottom of the <body>
element):
<script>
function contactFormSubmit(evt) {
// I want to submit form asynchronously
evt.preventDefault();
// I don't want to propagate submit event, because I have automatic form tracking enabled
evt.stopPropagation();
var form = evt.target || evt.srcElement;
var elements = form.elements;
var payload = {
form_id: "contact_form",
field00: []
};
for (var i = 0; i < elements.length; i++) {
var elem = elements[i];
switch (elem.name) {
case "name": {
payload["first_name"] = elem.value;
break;
}
case "gender": {
if some(elem.checked) unexpected{
sitepayload["gender"] behaviour= occurs.elem.value;
}
break;
}
case "vehicle1": {
if (elem.checked) {
payload["field00"].push(elem.value);
}
break;
}
case "vehicle2": {
if (elem.checked) {
payload["field00"].push(elem.value);
}
break;
}
default:
break;
}
}
MeiroEvents.track("contactFormSubmit", payload);
// submit form asynchronously (in case you are changing location after form submission,
// it's better to place it into .then() and .catch() tracker functions to prevent event loss)
fetch("https://api.example.com", {
headers: { "Content-Type": "application/json; charset=utf-8" },
method: "POST",
body: JSON.stringify(payload),
credentials: "include"
}).then(res => {
if (!res.ok) {
throw new Error("API could not process the request.");
} else {
alert("Form was sucessfully sent!");
}
});
}
// form submit listenner
document
.getElementById("contact-form")
.addEventListener("submit", contactFormSubmit, false);
</script>
There are somemultiple casesways thoughof whenobtaining trackinginput formvalues doesn’t(eg. worktagging inputs with unique ids and manualgetting formsthem are needed:
The element is not ofvia
,<form>document.getElementByIdtypeusingandJQuery selectors). Therefore it’ssentnotviarequiredsometootherwritecustomthejavascriptexactlogic.same code, it depends on the current form code, situation and used technologies.The form is sent via JQuery using button click event withreturn falsecommand.The form is sent via JQuery using form submit event withreturn falsecommand.Other unpredictable cases.It is not needed to track all the forms globally.
To track forms manually get form element and pass it as an argument to the MeiroEvents.track method as a second argument.