Articles on: SaaS - Installation

Installing conversion snippet into Front End code

Steps to send Conversion Data



We do recommend sending the snippet from the 'backend'. See here how to add the snippet into your code.

If you still need to add it on the front end, see below some examples.

See first the intro to our installation again, as ideally you do add the snippet into the actual code.




THERE ARE 3 FUNNEL STEPS INVOLVED TO SEND A CONVERSION DATA TO REDITUS SNIPPET using the front end solution:

It is crucial to understand what is happening in background which will assist us in providing the right solution to address the bug/issue you are facing.


steps for conversion snippet


First step: Every time someone type in their email within your form, you will need to store the email value they typed temporarily inside the user’s browser cookie or localStorage.
Second step: Once the email value is stored, you will need to capture the stored email values and send it within the email variable within the conversion snippet.
Third step: Once the user finishes typing and submits the form, our conversion snippet will then receive the value within the email variable and then able to send that back to your conversion dashboard.

<Undefined> Value


Your email variable is not captured by the conversion snippet, hence sending <undefined> value
If you noticed in the conversion snippet, you will realize that it requires a compulsory variable to be sent back to Reditus server which is email:

gr('track', 'conversion', {

If the conversion is appearing on your dashboard, this is because of the following scenario below:

SUCCESS SCENARIO: Your email value exists



gr('track', 'conversion', {

However, if the conversion is not appearing on your dashboard, it may also mean this is what is happening:

FAIL SCENARIO: Your email value is undefined



gr('track', 'conversion', {

In order to verify that, you can test copying gr(’track’ , ’conversion’) to your Google Chrome’s Developer Console where you will receive the same error:

error conversion snippet

When this happens, our conversion snippet will never run or even if it’s initiated, an undefined value would be rejected by Reditus servers hence giving you the no conversion error from the dashboard.

[HTML / JavaScript]


Possible Problem 1: Email value is not captured properly


html

Let’s say your form code looks something like this in the source code:

<input id="firstname" name="firstname" placeholder="First Name" required type="text" value="">
<input id="lastname" name="lastname" placeholder="Last Name" required type="text" value="">
<input id="username" name="username" placeholder="Username" required type="text" value="">


And it looks like this on the front-end:

form

From the source code, we now know that every input within the email field will be stored here:

BEFORE SOMEONE TYPES IN THEIR EMAIL


<input id="email_create" name="email"
AFTER SOMEONE TYPES IN THEIR EMAIL



<input id="email_create" name="email"

SOLUTION 1: Debug Using Chrome Developer Console
Use a function called:

document.getElementById(’email_create’).value
in order to return the value of the email to the Console. The id we use here is email_create as an example (refer to the code above) but it can be anything as long as it refers back to the exact id of the email input that you’ve named in your form code.


email input

After Email Input



SOLUTION 2: Include function in source code
Now that we’re able to grab the data in the Console, how do we store that in the user’s browser?

Paste the following JavaScript function below in your source code:

<script>
function grabEmailForReditus() {
var email_data = document.getElementById('email_create').value
return email_data }
</script>

And then in your code, place it somewhere at the top or bottom of your form code.

IN HTML

<script>
function grabEmailForReditus() {
var email_data = document.getElementById('email_create').value
return email_data }
</script>


<Your form code code goes here>
Or alternatively, you can actually create this variable in Google Tag Manager as well under Variables section.

IN GOOGLE TAG MANAGER



Possible Problem 2: Your email value contains an array and not a single object
WRONG WAY TO SEND

Let’s assume your form_data is a JSON array like this below:

const form_data = {

        company_name:companyName,
        company_state:state,
        company_structure:structure,
        company_suffix:suffix,
        company_members:members,
        phone:cPhone,
        email:cEmail,
        full_name:cName,
        ssn_or_itin:SSNYN,
        plan,
        planId,
        stateId,
        termsAgree:agree,
        country_c,
        country_r
      }


If that's the case, then gr(track) will never pass because it only seeks a single email value and not an array.

You will need to isolate the email value from the form_data variable and create something like this below:

SOLUTION
CORRECT WAY TO SEND

First step: Perform JSON parse on the form_data variable.

var form_json = JSON.parse(form_data);
Second step: Then use the (.) function to grab the single email value from the parsed form_json:

var form_email = form_json.email
Third step: Then, once value is acquired, input it within the snippet:

gr ('track','conversion', { email: form_email });

Email value not captured by conversion Snippet
PROBLEM AT FUNNEL STEP 2: The email value saved in a function’s variable earlier in Step 1 is not captured by the conversion snippet.




CHECK YOUR FUNCTION’S TRIGGER
Let’s go back to the function we created earlier in Step 1.

function grabEmailForReditus() {
var email_data = document.getElementById('email_create').value
return
Every function requires success triggers - this means when do we want the email_data is stored and when do we want the conversion snippet to receive that information:

gr('track', 'conversion', {
And what we want to do is we want to tell the function to provide the email_data to Reditus conversion snippet if the value of grabEmailForReditus() exists.

function grabEmailForReditus() {
// This grabs user's form input and store it inside a variable
var email_data = document.getElementById('email_create').value

// This checks if data of the above exists
if (email_data) {

// If exists, then send the data to the following below
gr('track','conversion', {email:

CHECK YOUR TRIGGER ARRANGEMENT
It is important that all the functions are working in a perfect order or else the email data is not going to flow nicely.

SUCCESS SCENARIO




Remember the data flow steps we mention earlier towards the beginning of this article?

FAIL SCENARIOS
Here are 2 common examples made by some of our clients which caused the tracking to fail:

SCENARIO 1




Here a function to pass that email data to gr(track) runs first before the email input from the form could be stored. This means there’s no email data that is going to be sent because it will return undefined.


SCENARIO 2




Here the gr(track) function is triggered first upon form submission whereas the other 2 steps were only happening later. This too will cause no email data being sent to the dashboard where it will return undefined.



VARIABLE VALUE IS CLEARED POST FORM SUBMIT
Another common thing to remember is that variables are normally cleared by default as soon as someone clicks Form Submit and the window refreshes.

2 ways to prevent the email variable’s value being cleared if you intend to trigger the gr(track) right after Form Submission:

1) Save that email variable’s value within the Cookie

<script>
(function(){
var cookieName = "emailVar"; // Name of your cookie
var cookieValue = "true"; // Value of your cookie
var expirationTime = 2592000; // One month in seconds
expirationTime = expirationTime * 1000; // Converts expirationtime to milliseconds
var date = new Date();
var dateTimeNow = date.getTime();

date.setTime(dateTimeNow + expirationTime); // Sets expiration time (Time now + one month)
var date = date.toUTCString(); // Converts milliseconds to UTC time string
document.cookie = cookieName+"="+cookieValue+"; SameSite=None; Secure; expires="+date+"; path=/; domain=." + location.hostname.replace(/^www\./i, ""); // Sets cookie for all subdomains
})();
</script>
2) Prevent form default refresh action

Replace that with your own function that POST the form data to the destination API that you intended while running a function that stores the email data variable data and initiate our gr(track) snippet if the email variable exists.

function mySubmitFunction(e) {
e.preventDefault();
grabEmailforReditus();
return false;
}
[REACT]
Email value not stored in the cookie




Let’s say your form’s React code looks something like this:

import logo from './logo.svg';
import './App.css';
import React from "react";
import ReactDOM from "react-dom";
import { Formik, Field, Form } from "formik";

function App() {
return (
<div className="App">
<h1>Contact Us</h1>
<Formik
initialValues={{ name: "", email: "" }}
onSubmit={async (values) => {
await new Promise((resolve) => setTimeout(resolve, 500));
alert(JSON.stringify(values, null, 2));
}}
>
<Form>
<Field name="name" type="text" />
<Field name="email" type="email" />
<button type="submit">Submit</button>
</Form>
</Formik>
</div>
);
}

export default App;
ReactDOM.render(<App />, document.getElementById("root"));
And it looks like this on the front-end:




USE GOOGLE TAG MANAGER TO SOLVE THIS

1) Ensure to install Google Tag Manager within your React’s App.JS code and not from the HTML’s code.

WRONG

<!doctype html>
<html lang="en">
<head>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-PTJWJF7');</script>
<!-- End Google Tag Manager -->
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Web site created using create-react-app" />
<link rel="apple-touch-icon" href="/logo192.png" />
<link rel="manifest" href="/manifest.json" />
<title>React App</title>
<script defer="defer" src="./static/js/main.338afb88.js"></script>
<link href="./static/css/main.073c9b0a.css" rel="stylesheet">
</head>
<body>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-PTJWJF7"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
Why is it wrong?

Since the App’s code is wrapped within our <root> div that is hidden within our HTML code, it is impossible for Tag Manager to listen to any changes happening in the React code.
If you have installed any security modules within your React app, they may block any connection from gtm.js attempting to access the form input within your App.js’s React code.

CORRECT

Install React-GTM-Module library to your local React app.

npm install react-gtm-module
Add the following lines below (in bold) to your React’s app JS code:

import logo from './logo.svg';
import './App.css';
import React from "react";
import ReactDOM from "react-dom";
import { Formik, Field, Form } from "formik";

//Add these lines below to enable GTM


2) Once Google Tag Manager is installed, test it using Google Tag Manager Debug Console and Tag Assistant.




3A) METHOD 1: Getting Form Values from React using JavaScript's getElement via GTM Variables
https://www.loom.com/share/3c3c7232099b489db9c03b5844c5b679?sid=e15e97e9-337e-4004-8efb-dd364dcd67c0

Create a function within Google Tag Manager that will listen to email form input happening within your React’s form and name that variable email_data

function grabEmailforReditus() {
var email_data = document.getElementsByName("email")[0].value;
if (email_data)
return email_data
}




3B) METHOD 2: Getting Form Values from React using localStorage (setState) & dataLayer.push
Should you are unable to capture your form data using JavaScript getElement function, alternatively, you can actually store form input into your localStorage and push that data to GTM’s dataLayer.

https://www.loom.com/share/918515adfe2947d0bc0f914f121d73da?sid=c8e2e1d6-f138-40bb-bd5b-8cb00611bd28

In order to replicate the method shown in the video, feel free to copy this React code below and modify accordingly:

import logo from './logo.svg';
import './App.css';
import ReactDOM from "react-dom";
import { Formik, Field, Form } from "formik";
import TagManager from 'react-gtm-module'
import React, { Component } from 'react';
export default class FormDataComponent extends Component {
userData;
constructor(props) {
super(props);
this.onChangeName = this.onChangeName.bind(this);
this.onChangeEmail = this.onChangeEmail.bind(this);
this.onChangePhone = this.onChangePhone.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
name: '',
email: '',
phone: ''
}
}

// Form Events
onChangeName(e) {
this.setState({ name: e.target.value })
}
onChangeEmail(e) {
this.setState({ email: e.target.value })
}
onChangePhone(e) {
this.setState({ phone: e.target.value })
}
onSubmit(e) {
e.preventDefault()
this.setState({
name: '',
email: '',
phone: ''
})

4) Now remember that GTM can only track 2 things from your React code.

a) History Changes

You will need to enable this from GTM by creating a trigger for All History Changes





b) Click Events

Create a trigger for All Element Clicks as well.




5) Look for the email_data to appear in GTM console under Click event

In this screenshot, I name the variable as EmailVar2 and put the following test email nik-reacttest-submitform@gmail.com:





Email value not captured by snippet
PROBLEM AT FUNNEL STEP 2: The email value saved in a function’s variable earlier in Step 1 is not captured by the conversion snippet.





CHECK YOUR FUNCTION’S TRIGGER SETUP IN GTM

Create a trigger where GTM will only run the above function which is upon Button Click event.




Remember that the above is an example assuming that you have a button with Click Text containing Submit.

What if I have other types of button with different labels?

Fret not. Always use back the GTM console to look for unique variable and parameters that you can use in each Click event that GTM can track within your React form.


CREATE A NEW TAG THAT WILL SEND THE SAVED EMAIL VARIABLE INTO REDITUS CONVERSION SNIPPET

Then, create a new tag that will contain the above trigger that we created and the {{ email_data }} function that we created in the earlier steps.




Or copy the following below in order to create new tag:

<script>gr('track', 'conversion', { email:
💡
If you need help during the setup, feel free to reach out to us as we do offer live chat and technical assistance.

Updated on: 07/11/2023

Was this article helpful?

Share your feedback

Cancel

Thank you!