Search code examples
ajaxknockout.jsgoogle-analytics-api

Google Analytics Send Event on Ajax Success Not Working


I have a Process Transaction Knockout method that returns a transaction status and depending on that status I want analytics.js event to be sent. I've used analytics-debug.js and in the console it says "Send finished" but the event never shows up in Google Analytics.

The send event works if it is before or after the ajax request but not if it is in the success or done callbacks.

$.ajax({
    url: '/ProcessTransaction',
    type: 'post',
    data: 'data',
    contentType: 'application/json',
    success: function (result) {
        if (result.StatusCode == 1 || result.StatusCode == 4) {
            var subtotal = 7.95;
            var enrollmentFee = 25;
            var total = subtotal + enrollmentFee;
            ga('ec:addProduct', {
                'id': 'P12345',
                'name': 'Test Product 1',
                'category': 'Products',
                'brand': 'Brand',
                'price': subtotal,
                'quantity': 1
            });
            ga('ec:setAction', 'purchase', {
                'id': 'T12345',
                'affiliation': 'TestSite',
                'revenue': total,
                'tax': enrollmentFee,
            });
            ga('send', 'event', 'Review', 'transaction', 'approved', total);
            $('#submitpaymentbtn').data('loading-text', 'Approved!').button('loading');
            window.location.href = '@Url.Action("Confirmation", new { ParticipantId = Participant.ParticipantId })';
        }
        else {
            $('#modal-error').modal();
        }
    }
});

Solution

  • Send event does not allow decimal for event value. Math.round(total) fixes the issue. Even thought the analytics debug says event sent, it is never accepted or logged because the value must be an integer.

    ga('send', 'event', 'Review', 'transaction', 'approved', Math.round(total));