advancedforms / advanced-forms

WordPress plugin to create forms using Advanced Custom Fields
75 stars 16 forks source link

Google Analytics tracking #87

Open edwardjosephbennett opened 4 years ago

edwardjosephbennett commented 4 years ago

Hi,

After much documentation reading, Google searching & code reading, I was wondering whether there is an official way to trigger google analytics events on the successful sending of a form. My normal solution, would be to fire it using javascript based on a DOM event outputted from a form, which we can do on plugins like ContactForm7 with:

document.addEventListener('wpcf7mailsent', function() {
// Do some code here
})

Is there anything similar to that within the Advanced Forms plugin? I know that ACF has it's own JS API, but from looking through plugin code in this repo and the documentation, I'm not sure what events I should use? Ideally I'd like this to be a Javascript based solution, rather than server side, although open to anything.

For reference, here is the way I am doing it currently, but it feels hacky, as if a class name changes, or the plugin structure changes, this could easily break:

if($('form.af-form div.af-success').length > 0) {
console.log('this works');
}

I should mention, I am using the free version of the plugin.

Thanks in advance. Ed

fabianlindfors commented 4 years ago

Hi!

I'm not very familiar with Google Analytics but I think the best way to do this is probably to send the event from the server-side. GA seems to have an API for this: https://developers.google.com/analytics/devguides/collection/protocol/v1/ and you can use this hook to send the event after a submission: https://advancedforms.github.io/guides/basic/processing-form-submissions/.

Would that work?