I'm trying to capture form input field values, and send them upon form submission to a 3rd-party API endpoint using Google Tag Manager.
What I did so far:
I managed to define data layer variables so I can see the desired form field inputs in the data layer once the form has been submitted. In Preview-mode it looks like this:
dataLayer.push({event: "gtm.formSubmit", ...})
What am I still missing?
Now that the values are in the data layer, I need to send them to a REST API endpoint.
How can I achieve this using a Custom HTML tag?
You can just create a custom html tag and put the code below.
But you need to modify some part of it.
<script>
(function(){
try {
var dlvEmail = {{dlv - contact form email}};
var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // Regular expression for basic email validation
if (dlvEmail && emailRegex.test(dlvEmail)) {
var xhr = new XMLHttpRequest();
var endpoint = 'https://example.com/api';
// modify to the API endpoint you need
xhr.open('POST', endpoint, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({ key: dlvEmail }));
// change the key to the API document need.
} else {
console.error('Invalid email format');
}
} catch (error) {
console.error('An error occurred during the request:', error);
}
})();
</script>
You can test it then if everything work. You can remove the console.log within the code to make sure no interrupt the console.
If the API document need some additional auth.
You can just modify the code or checking how xhr can implement the auth.