Не передаются события в dataLayer при добавлении товара в корзину

Тема в разделе "Общие вопросы", создана пользователем 5_minutes_Turkish, 9 июл 2022.

  1. 5_minutes_Turkish

    5_minutes_Turkish Новичок

    Сообщения:
    1
    Симпатии:
    0
    Добрый день. Столкнулся с проблемой когда не отрабатывает код на передачу данных при добавлении товара в корзину.
    Версия ocStore 2.3.0.2.4

    При этом при удалении товара скрипты отлично отрабатывают (((
    Может кто знает в чем причина или сталкивался с подобным уже?

    Скрипты на пуш в ДЛ добавляю в стандартный common.js - в функции переменной cart соответственно

    К скриптам добавил коменты // СКРИПТ КОТОРЫЙ ПУШИТ ПРИ ДОБАВЛЕНИИ / УДАЛЕНИИ чтоб понятно было где что

    Выглядит примерно так:
    Код:
    // Cart add remove functions
    var cart = {
        'add': function(product_id, quantity) {
            $.ajax({
                url: 'index.php?route=checkout/cart/add',
                type: 'post',
                data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
                dataType: 'json',
                beforeSend: function() {
                   
                },
                complete: function() {
                   
                },
                success: function(json) {
                    $('.alert, .text-danger').remove();
    
                    if (json['redirect']) {
                        location = json['redirect'];
                    }
    
                    if (json['success']) {
                        // Need to set timeout otherwise it wont update the total
                        setTimeout(function () {
                            $('.header-item.cardIcon span').html(json['total_cart']);
                        }, 100);
    
                               
                        // dataLayer.push({  
                        //     'event': 'addToCart',   //added for test
                        //         'ecommerce': {    
                        //             'currencyCode': 'RUB',    
                        //             'add': {                                    
                        //             'products': [{                      
                        //             'name': '' + json['name'] + '',        
                        //             'id': '' + product_id + ''    
                        //             }]    
                        //         }  
                        //     }
                        // });
                       
                        // СКРИПТ КОТОРЫЙ ПУШИТ ПРИ ДОБАВЛЕНИИ
                        dataLayer.push({
                            "ecommerce": {   //added for test
                                "currencyCode": "RUB",  
                                "add": {
                                    "products": [
                                        {
                                            "id": '' + product_id + '',
                                            "name": '' + json['name'] + '',
                                            "quantity": 1
                                        }
                                    ]
                                }
                            }
                        });
                        // СКРИПТ КОТОРЫЙ ПУШИТ ПРИ ДОБАВЛЕНИИ
    
    
                        //$('html, body').animate({ scrollTop: 0 }, 'slow');
    
                        $('#cart').load('index.php?route=common/cart/info #cart .load');
                        $('#currentTotal').text(json['subtotal']);
                    }
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
                }
            });
        },
        'update': function(key, quantity) {
            $.ajax({
                url: 'index.php?route=checkout/cart/edit',
                type: 'post',
                data: 'key=' + key + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
                dataType: 'json',
                beforeSend: function() {
                   
                },
                complete: function() {
                   
                },
                success: function(json) {
                    // Need to set timeout otherwise it wont update the total
                    setTimeout(function () {
                        $('.header-item.cardIcon span').html(json['total_cart']);
                    }, 100);
    
                    if (getURLVar('route') == 'checkout/cart' || getURLVar('route') == 'checkout/checkout') {
                        location = 'index.php?route=checkout/cart';
                    } else {
                        $('#cart').load('index.php?route=common/cart/info #cart .load');
                        $('#currentTotal').text(json['subtotal']);
                    }
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
                }
            });
        },
        'remove': function(key) {
            $.ajax({
                url: 'index.php?route=checkout/cart/remove',
                type: 'post',
                data: 'key=' + key,
                dataType: 'json',
                beforeSend: function() {
                   
                },
                complete: function() {
                   
                },
                success: function(json) {
                    // СКРИПТ КОТОРЫЙ ПУШИТ ПРИ УДАЛЕНИИ
                    dataLayer.push({   //added for test
                        'event': 'removeFromCart',  
                        'ecommerce': {    
                        'remove': {                                
                            'products': [{                      
                                'name': '' + json['name'] + '',          
                                'id': '' + key + ''                        
                        }]    
                        }  
                    }
                    });
                    // СКРИПТ КОТОРЫЙ ПУШИТ ПРИ УДАЛЕНИИ
                   
                    // Need to set timeout otherwise it wont update the total
                    setTimeout(function () {
                        $('.header-item.cardIcon span').html(json['total_cart']);
                    }, 100);
                   
                    var now_location = String(document.location.pathname);
    
                    if ((now_location == '/cart/') || (now_location == '/checkout/') || (getURLVar('route') == 'checkout/cart') || (getURLVar('route') == 'checkout/checkout')) {
                        location = 'index.php?route=checkout/cart';
                    } else {
                        $('#cart').load('index.php?route=common/cart/info #cart .load');
                    }
                    if($('#custom-cart').length){
                        custom_block.render('cart');
                        custom_block.render('total');
                        $('#currentTotal').text(json['subtotal']);
                    }
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
                }
            });
        }
    }
    Я думал мб что не так с конструкцией которую пушу при добавлении товара в корзину (хотя по идее должно быть пофиг)... но все тщетно ((
    В общем странная штука.. не понимаю в чем проблема
     
  2. Blast

    Blast Продвинутый пользователь

    Сообщения:
    209
    Симпатии:
    72
    если добавляете из карточки товара, то там отдельный скрипт во вьюхе product.tpl