简体   繁体   中英

Problems Populating the Google Tag Manager datalayer

For the past few days I have been trying to populate the Google Tag Manager datalayer on the OpenCart product page when the button "Add to Cart" is clicked.

I understand that I need to use the push method, but I can't figure out where to nest it since I have no HTML button just a JavaScript function.

The function:

 <script type="text/javascript"><!-- $('#button-cart').on('click', function() { $.ajax({ url: 'index.php?route=checkout/cart/add', type: 'post', data: $('#product input[type=\\'text\\'], #product input[type=\\'hidden\\'], #product input[type=\\'radio\\']:checked, #product input[type=\\'checkbox\\']:checked, #product select, #product textarea'), dataType: 'json', beforeSend: function() { $('#button-cart').button('loading'); }, complete: function() { $('#button-cart').button('reset'); }, success: function(json) { $('.alert, .text-danger').remove(); $('.form-group').removeClass('has-error'); if (json['error']) { if (json['error']['option']) { for (i in json['error']['option']) { var element = $('#input-option' + i.replace('_', '-')); if (element.parent().hasClass('input-group')) { element.parent().after('<div class="text-danger">' + json['error']['option'][i] + '</div>'); } else { element.after('<div class="text-danger">' + json['error']['option'][i] + '</div>'); } } } if (json['error']['recurring']) { $('select[name=\\'recurring_id\\']').after('<div class="text-danger">' + json['error']['recurring'] + '</div>'); } // Highlight any found errors $('.text-danger').parent().addClass('has-error'); } if (json['success']) { $('.breadcrumb').after('<div class="alert alert-success">' + json['success'] + '<button type="button" class="close" data-dismiss="alert">&times;</button></div>'); $('#cart > button').html('<i class="fa fa-shopping-cart"></i> ' + json['total']); $('html, body').animate({ scrollTop: 0 }, 'slow'); $('#cart > ul').load('index.php?route=common/cart/info ul li'); } }, error: function(xhr, ajaxOptions, thrownError) { alert(thrownError + "\\r\\n" + xhr.statusText + "\\r\\n" + xhr.responseText); } }); });

I turned the internet up side down but found no solution to this. Any help is appreciated.

In the code from your question you have already initialized the click handler for the "Add to cart" button. Put your dataLayer logic inside the click handler.

$('#button-cart').on('click', function() {
    window.dataLayer = window.dataLayer || [];
    dataLayer.push({
        'event': 'button-add-to-cart-click'
    });
    // other code
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM