How to track form submissions in Elementor Forms?

This one was a doosey!

A customer was using Elementor's form builder to track submissions. They wanted to sync fields + email address with Bento.

The follow script was what I wrote to achieve that. You can copy and paste this in the footer of the site (make sure it's the last to load) or just use Bento Personalization to inject it after Bento.js loads (safest way). 

Note: the key part here is that we remap the fields via the variable keysMap. If you add more fields make sure you add them here to be remapped otherwise fields may not look as desired in Bento. 

function getFormData($form) {
    var unindexed_array = $form.find("input[type!='password']").serializeArray();
    var indexed_array = {};
    bento$.map(unindexed_array, function(n, i){
      indexed_array[n['name']] = n['value'];
    });
    return indexed_array;
};

function stringify(object) {
  if (typeof(JSON) !== "undefined" && typeof(JSON.stringify) !== "undefined") {
    return JSON.stringify(object);
  } else {
    return "";
  }
};

function elementToObject(element) {
  var object = {};
  object['element'] = element.tagName;
  if (element.tagName.toLowerCase() != 'form') {
    object['text'] = bento$(element).text();
  }
  bento$.each(element.attributes, function() {
    if (this.specified) {
      object[this.name] = this.value;
    }
  });
  return object;
};

renameKeys = (keysMap, obj) =>
  Object.keys(obj).reduce(
    (acc, key) => ({
      ...acc,
      ...{ [keysMap[key] || key]: obj[key] }
    }),
    {}
);

keysMap = {
  'form_fields[email]': 'email',
  'form_fields[fname]': 'first_name',
  'form_fields[lname]': 'last_name',
  'form_fields[phone]': 'phone',
};

bento$(document).on('submit_success', function(event){
    event.preventDefault();
    var payload = elementToObject(event.target);
    payload.data = getFormData(bento$(event.target));
    bento.updateFields(renameKeys(keysMap, payload.data));
    bento.track("$optIn", {});
    $(this).submit();
});
Leave a reply