Custom script to send GA purchase event doesn't work anymore with GTM












0















I had this custom script sending a GA purchase event working fine, but then I switched to Google Tag Manager and the script doesn't work anymore.



The logic is that when someone purchases a service, they're directed to a thank you page, where the transaction data is populated into the URL from the PHP charge.



Then this script fires on that page and reads the URL to assign the transaction info, and send to analytics:



var pkg,
value,
ID = window.location.href.split("=")[1];

if (window.location.href.indexOf("starter") > -1) {
value = 150;
pkg = "Starter";
} else if (window.location.href.indexOf("professional") > -1) {
value = 250;
pkg = "Professional";
} else if (window.location.href.indexOf("entrepreneur") > -1) {
value = 350;
pkg = "Entrepreneur";
} else {
value = 0;
pkg = "error";
}

if (value > 0) {
// Google Analytics Ecommerce Tracking
gtag('event', 'purchase', {
"transaction_id": ID,
"value": value,
"currency": "USD",
"items": [
{
"id": pkg,
"name": pkg,
"quantity": 1,
"price": value
}
]
});
}


With GTM, I have this script as a "custom html" tag.



If I do a test charge and populate that URL/thank you page, I get a console error saying gtag() is not a function.



So I tried ga(), that doesn't produce an error, but it also doesn't send the event.



Then I read about dataLayer, so I tried wrapping it in that instead of ga() / gtag():



dataLayer.push({
'event', 'purchase', {
"transaction_id": ID,
"value": value,
"currency": "USD",
"items": [
{
"id": pkg,
"name": pkg,
"quantity": 1,
"price": value
}
]
}
});


And that gave me a javascript error. Seems I might also need to put an empty dataLayer variable somewhere on the page, but not sure how this works.



Any ideas? Alternative, should I be sending this event via PHP instead? (never used PHP with GA so wasn't sure).










share|improve this question



























    0















    I had this custom script sending a GA purchase event working fine, but then I switched to Google Tag Manager and the script doesn't work anymore.



    The logic is that when someone purchases a service, they're directed to a thank you page, where the transaction data is populated into the URL from the PHP charge.



    Then this script fires on that page and reads the URL to assign the transaction info, and send to analytics:



    var pkg,
    value,
    ID = window.location.href.split("=")[1];

    if (window.location.href.indexOf("starter") > -1) {
    value = 150;
    pkg = "Starter";
    } else if (window.location.href.indexOf("professional") > -1) {
    value = 250;
    pkg = "Professional";
    } else if (window.location.href.indexOf("entrepreneur") > -1) {
    value = 350;
    pkg = "Entrepreneur";
    } else {
    value = 0;
    pkg = "error";
    }

    if (value > 0) {
    // Google Analytics Ecommerce Tracking
    gtag('event', 'purchase', {
    "transaction_id": ID,
    "value": value,
    "currency": "USD",
    "items": [
    {
    "id": pkg,
    "name": pkg,
    "quantity": 1,
    "price": value
    }
    ]
    });
    }


    With GTM, I have this script as a "custom html" tag.



    If I do a test charge and populate that URL/thank you page, I get a console error saying gtag() is not a function.



    So I tried ga(), that doesn't produce an error, but it also doesn't send the event.



    Then I read about dataLayer, so I tried wrapping it in that instead of ga() / gtag():



    dataLayer.push({
    'event', 'purchase', {
    "transaction_id": ID,
    "value": value,
    "currency": "USD",
    "items": [
    {
    "id": pkg,
    "name": pkg,
    "quantity": 1,
    "price": value
    }
    ]
    }
    });


    And that gave me a javascript error. Seems I might also need to put an empty dataLayer variable somewhere on the page, but not sure how this works.



    Any ideas? Alternative, should I be sending this event via PHP instead? (never used PHP with GA so wasn't sure).










    share|improve this question

























      0












      0








      0








      I had this custom script sending a GA purchase event working fine, but then I switched to Google Tag Manager and the script doesn't work anymore.



      The logic is that when someone purchases a service, they're directed to a thank you page, where the transaction data is populated into the URL from the PHP charge.



      Then this script fires on that page and reads the URL to assign the transaction info, and send to analytics:



      var pkg,
      value,
      ID = window.location.href.split("=")[1];

      if (window.location.href.indexOf("starter") > -1) {
      value = 150;
      pkg = "Starter";
      } else if (window.location.href.indexOf("professional") > -1) {
      value = 250;
      pkg = "Professional";
      } else if (window.location.href.indexOf("entrepreneur") > -1) {
      value = 350;
      pkg = "Entrepreneur";
      } else {
      value = 0;
      pkg = "error";
      }

      if (value > 0) {
      // Google Analytics Ecommerce Tracking
      gtag('event', 'purchase', {
      "transaction_id": ID,
      "value": value,
      "currency": "USD",
      "items": [
      {
      "id": pkg,
      "name": pkg,
      "quantity": 1,
      "price": value
      }
      ]
      });
      }


      With GTM, I have this script as a "custom html" tag.



      If I do a test charge and populate that URL/thank you page, I get a console error saying gtag() is not a function.



      So I tried ga(), that doesn't produce an error, but it also doesn't send the event.



      Then I read about dataLayer, so I tried wrapping it in that instead of ga() / gtag():



      dataLayer.push({
      'event', 'purchase', {
      "transaction_id": ID,
      "value": value,
      "currency": "USD",
      "items": [
      {
      "id": pkg,
      "name": pkg,
      "quantity": 1,
      "price": value
      }
      ]
      }
      });


      And that gave me a javascript error. Seems I might also need to put an empty dataLayer variable somewhere on the page, but not sure how this works.



      Any ideas? Alternative, should I be sending this event via PHP instead? (never used PHP with GA so wasn't sure).










      share|improve this question














      I had this custom script sending a GA purchase event working fine, but then I switched to Google Tag Manager and the script doesn't work anymore.



      The logic is that when someone purchases a service, they're directed to a thank you page, where the transaction data is populated into the URL from the PHP charge.



      Then this script fires on that page and reads the URL to assign the transaction info, and send to analytics:



      var pkg,
      value,
      ID = window.location.href.split("=")[1];

      if (window.location.href.indexOf("starter") > -1) {
      value = 150;
      pkg = "Starter";
      } else if (window.location.href.indexOf("professional") > -1) {
      value = 250;
      pkg = "Professional";
      } else if (window.location.href.indexOf("entrepreneur") > -1) {
      value = 350;
      pkg = "Entrepreneur";
      } else {
      value = 0;
      pkg = "error";
      }

      if (value > 0) {
      // Google Analytics Ecommerce Tracking
      gtag('event', 'purchase', {
      "transaction_id": ID,
      "value": value,
      "currency": "USD",
      "items": [
      {
      "id": pkg,
      "name": pkg,
      "quantity": 1,
      "price": value
      }
      ]
      });
      }


      With GTM, I have this script as a "custom html" tag.



      If I do a test charge and populate that URL/thank you page, I get a console error saying gtag() is not a function.



      So I tried ga(), that doesn't produce an error, but it also doesn't send the event.



      Then I read about dataLayer, so I tried wrapping it in that instead of ga() / gtag():



      dataLayer.push({
      'event', 'purchase', {
      "transaction_id": ID,
      "value": value,
      "currency": "USD",
      "items": [
      {
      "id": pkg,
      "name": pkg,
      "quantity": 1,
      "price": value
      }
      ]
      }
      });


      And that gave me a javascript error. Seems I might also need to put an empty dataLayer variable somewhere on the page, but not sure how this works.



      Any ideas? Alternative, should I be sending this event via PHP instead? (never used PHP with GA so wasn't sure).







      google-analytics google-tag-manager






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 23 '18 at 13:14









      Joe LannenJoe Lannen

      277418




      277418
























          2 Answers
          2






          active

          oldest

          votes


















          0














          Your code for the datalayer.push will work either when you include it after the GTM code (because GTM initializes the dataLayer variable), or if you declare the dataLayer variable before your push (and before the GTM code, if you initialize the dataLayer after the GTM code GTM will not work properly).



          The indefatigable Simo Ahava has of course a blog post on datalayer initialization that should answer all your questions.






          share|improve this answer

































            0














            If anyone finds this in the future, here's what worked.



            CODE:



            <script>
            var value, ID, pkg;

            // populate variables

            // push vars to the datalayer
            if (value > 0) {
            dataLayer = ;
            dataLayer.push({
            'transactionId': ID,
            'transactionTotal': value,
            'transactionProducts': [{
            'sku': pkg,
            'name': pkg,
            'price': value,
            'quantity': 1}],
            'event' : 'purchase'
            });
            }

            // GTM script here
            </script>


            GOOGLE TAG MANAGER:



            Then I created a Tag in GTM.



            Tag Type: Google Analytics - Universal Analytics



            Track Type: Transaction



            Trigger: On thank you page (where the script is)



            And now, transactions are tracking perfectly :D






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447414%2fcustom-script-to-send-ga-purchase-event-doesnt-work-anymore-with-gtm%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              Your code for the datalayer.push will work either when you include it after the GTM code (because GTM initializes the dataLayer variable), or if you declare the dataLayer variable before your push (and before the GTM code, if you initialize the dataLayer after the GTM code GTM will not work properly).



              The indefatigable Simo Ahava has of course a blog post on datalayer initialization that should answer all your questions.






              share|improve this answer






























                0














                Your code for the datalayer.push will work either when you include it after the GTM code (because GTM initializes the dataLayer variable), or if you declare the dataLayer variable before your push (and before the GTM code, if you initialize the dataLayer after the GTM code GTM will not work properly).



                The indefatigable Simo Ahava has of course a blog post on datalayer initialization that should answer all your questions.






                share|improve this answer




























                  0












                  0








                  0







                  Your code for the datalayer.push will work either when you include it after the GTM code (because GTM initializes the dataLayer variable), or if you declare the dataLayer variable before your push (and before the GTM code, if you initialize the dataLayer after the GTM code GTM will not work properly).



                  The indefatigable Simo Ahava has of course a blog post on datalayer initialization that should answer all your questions.






                  share|improve this answer















                  Your code for the datalayer.push will work either when you include it after the GTM code (because GTM initializes the dataLayer variable), or if you declare the dataLayer variable before your push (and before the GTM code, if you initialize the dataLayer after the GTM code GTM will not work properly).



                  The indefatigable Simo Ahava has of course a blog post on datalayer initialization that should answer all your questions.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 23 '18 at 16:30

























                  answered Nov 23 '18 at 13:49









                  Eike PierstorffEike Pierstorff

                  24.9k32345




                  24.9k32345

























                      0














                      If anyone finds this in the future, here's what worked.



                      CODE:



                      <script>
                      var value, ID, pkg;

                      // populate variables

                      // push vars to the datalayer
                      if (value > 0) {
                      dataLayer = ;
                      dataLayer.push({
                      'transactionId': ID,
                      'transactionTotal': value,
                      'transactionProducts': [{
                      'sku': pkg,
                      'name': pkg,
                      'price': value,
                      'quantity': 1}],
                      'event' : 'purchase'
                      });
                      }

                      // GTM script here
                      </script>


                      GOOGLE TAG MANAGER:



                      Then I created a Tag in GTM.



                      Tag Type: Google Analytics - Universal Analytics



                      Track Type: Transaction



                      Trigger: On thank you page (where the script is)



                      And now, transactions are tracking perfectly :D






                      share|improve this answer




























                        0














                        If anyone finds this in the future, here's what worked.



                        CODE:



                        <script>
                        var value, ID, pkg;

                        // populate variables

                        // push vars to the datalayer
                        if (value > 0) {
                        dataLayer = ;
                        dataLayer.push({
                        'transactionId': ID,
                        'transactionTotal': value,
                        'transactionProducts': [{
                        'sku': pkg,
                        'name': pkg,
                        'price': value,
                        'quantity': 1}],
                        'event' : 'purchase'
                        });
                        }

                        // GTM script here
                        </script>


                        GOOGLE TAG MANAGER:



                        Then I created a Tag in GTM.



                        Tag Type: Google Analytics - Universal Analytics



                        Track Type: Transaction



                        Trigger: On thank you page (where the script is)



                        And now, transactions are tracking perfectly :D






                        share|improve this answer


























                          0












                          0








                          0







                          If anyone finds this in the future, here's what worked.



                          CODE:



                          <script>
                          var value, ID, pkg;

                          // populate variables

                          // push vars to the datalayer
                          if (value > 0) {
                          dataLayer = ;
                          dataLayer.push({
                          'transactionId': ID,
                          'transactionTotal': value,
                          'transactionProducts': [{
                          'sku': pkg,
                          'name': pkg,
                          'price': value,
                          'quantity': 1}],
                          'event' : 'purchase'
                          });
                          }

                          // GTM script here
                          </script>


                          GOOGLE TAG MANAGER:



                          Then I created a Tag in GTM.



                          Tag Type: Google Analytics - Universal Analytics



                          Track Type: Transaction



                          Trigger: On thank you page (where the script is)



                          And now, transactions are tracking perfectly :D






                          share|improve this answer













                          If anyone finds this in the future, here's what worked.



                          CODE:



                          <script>
                          var value, ID, pkg;

                          // populate variables

                          // push vars to the datalayer
                          if (value > 0) {
                          dataLayer = ;
                          dataLayer.push({
                          'transactionId': ID,
                          'transactionTotal': value,
                          'transactionProducts': [{
                          'sku': pkg,
                          'name': pkg,
                          'price': value,
                          'quantity': 1}],
                          'event' : 'purchase'
                          });
                          }

                          // GTM script here
                          </script>


                          GOOGLE TAG MANAGER:



                          Then I created a Tag in GTM.



                          Tag Type: Google Analytics - Universal Analytics



                          Track Type: Transaction



                          Trigger: On thank you page (where the script is)



                          And now, transactions are tracking perfectly :D







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 30 '18 at 0:34









                          Joe LannenJoe Lannen

                          277418




                          277418






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447414%2fcustom-script-to-send-ga-purchase-event-doesnt-work-anymore-with-gtm%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Costa Masnaga

                              Fotorealismo

                              Sidney Franklin