Search code examples
javascriptgoogle-analyticsgoogle-analytics-apievent-tracking

How to track a form submission using Google Analytics


I wanted to track a simple contact us form submission and the code I used for this is,

form action="/contact-us/#wpcf7-f2017-p2044-o1" method="post" **onsubmit = "ga('send', 'event', 'Contact Form Submission', 'post', location.pathname, {
  nonInteraction: true});"** class="wpcf7-form sent" novalidate="novalidate"

It doesn't work and gives this error,

Uncaught SyntaxError: Unexpected token ILLEGAL VM300:1

Everything else in the Google Analytic account is working fine. May be because the developer has implemented the code inside a function?

ny help regarding this would be highly appreciated.

Thank you


Solution

  • You have a newline character in your string

    "ga('send', 'event', 'Contact Form Submission', 'post', location.pathname, {
      nonInteraction: true});"
    

    Removing it makes it work:

    "ga('send', 'event', 'Contact Form Submission', 'post', location.pathname, {nonInteraction: true});"
    

    The problem is explained here: JavaScript string with new line - but not using \n