Skip to content Skip to sidebar Skip to footer

Google Analytics - Using Get Instead Of Post

Ran into an issue where I need to use GET vs POST on a form method, but GATC cookie data is not being appended to the URL correctly, because the form's data is trumping Google's GA

Solution 1:

For future reference, in case anyone runs into the same issue, this is the solution I implemented. I lifted some code from the answer to this SO post, and combined it with the idea behind this post, where it localizes the GATC data, and adds hidden fields to the form for each one.

Resulting code:

$(document).ready(function() {
    $('#formId').submit(function(e) {

        try {

            e.preventDefault();

            var form = this;

            if (typeof _gat !== 'undefined') {

                _gaq.push(['_linkByPost', this]);

                var pageTracker = _gat._getTrackerByName();

                var url = pageTracker._getLinkerUrl(form.action);

                var match = url.match(/[^=&?]+\s*=\s*[^&#]*/g);

                for ( var i = match.length; i--; ) {

                    var spl = match[i].split("=");

                    var name = spl[0].replace("[]", "");

                    var value = spl[1];

                    $('<input>').attr({
                        type: 'hidden',
                        name: name,
                        value: value
                    }).appendTo(form);
                }
            }

            setTimeout(function() { form.submit(); }, 400);
        } catch (e) { form.submit(); }
    });
});

Solution 2:

You can use jQuery serialize to get the form's elements, then _getLinkerUrl to append the cross-domain tracking data

$('#formID').submit(function(e) {
  var pageTracker = _gat._getTrackerByName();
  var url = this.action + '?' + $(this).serialize();
  url = pageTracker._getLinkerUrl(url);
  if (this.target != '_blank') location.href = url;
  elsewindow.open(url);
});

Post a Comment for "Google Analytics - Using Get Instead Of Post"