Ninja Forms is one of the popular forms on WordPress. If you’re interested in tracking Ninja Forms and need to capture form submission events and user input values to enhance conversion tracking, then this tutorial is for you.
Ninja Form DataLayer Coder
<script>
/**
* Author: Md Hasanuzzamna
* Linkedin: https://linkedin.com/in/md-h
* Youtube: https://youtube.com/@leomeasure
* Email: info@leomeasure.com
*/
(function() {
function convertNinjaFieldsToInputs(fields) {
var inputs = {};
for (var key in fields) {
if (fields.hasOwnProperty(key)) {
var label = fields[key].label;
var slug = label.toLowerCase().replace(/ /g, "_");
var value = fields[key].value;;
if(slug === 'phone') {
value = value.replace(/[\(\)\s-]/g, '');
}
inputs[slug] = value;
}
}
return inputs;
}
jQuery(document).on('nfFormSubmitResponse', function(event, responseData, id) {
dataLayer.push({
event: 'ninja_form_submit',
form_id: responseData.id,
inputs: convertNinjaFieldsToInputs(responseData.response.data.fields),
});
});
})()
</script>