Search code examples
ajaxgoogle-analyticsmeasurement-protocol

How to use measurement protocol for desktop application


what I have tried is,

[with POST]

jQuery.support.cors = true;

$.ajax({
    url : "https://www.google-analytics.com/collect?v=1&tid=UA-XXXXXXXX-1&cid=e8efa9cb-7b9e-479e-b07b-1528547dcdb4&t=event&ec=UX&ea=click&z=123456",
    type : 'POST',
    cache : false,
    dataType : 'json',
    success:function(data) {
        alert("Success: " + JSON.stringify(data));
    },
    error: function(data) {
        alert("Failure: " + JSON.stringify(data));
    }
});

or [with GET]

jQuery.support.cors = true;

$.ajax({
    url : "https://www.google-analytics.com/collect?v=1&tid=UA-XXXXXXXX-1&cid=e8efa9cb-7b9e-479e-b07b-1528547dcdb4&t=event&ec=UX&ea=click&z=123456",
    dataType : 'json',
    success:function(data) {
        alert("Success: " + JSON.stringify(data));
    },
    error: function(data) {
        alert("Failure: " + JSON.stringify(data));
    }
});

Onclick of button I have added this code.

I'm getting status 200 but, In google analytics report [real time data] its showing No active users. And if I check previous days report its showing some count for user sessions.


Solution

  • There appears to be a bug in the way the measurement protocol is handling events. I have created an issue for this Here: Issue 848: Events not showing up on Real-time reports

    You don't send the Application variables the data will not be displayed in real-time reports. As soon as you send a request with it they pop up again but you loose them if you send another event without it. It is not document at this time that the application variables are required. Also a debug on your request comes back with valid hit data.

    https://www.google-analytics.com/debug/collect?v=1&tid=UA-xxxxx-1&cid=e8efa9cb-7b9e-479e-b07b-1528547dcdb4&t=event&ec=UX&ea=click&z=123456
    
    {
      "hitParsingResult": [ {
        "valid": true,
        "parserMessage": [ ],
        "hit": "/debug/collect?v=1\u0026tid=UA-xxxxx-1\u0026cid=e8efa9cb-7b9e-479e-b07b-1528547dcdb4\u0026t=event\u0026ec=UX\u0026ea=click\u0026z=123456"
      } ],
      "parserMessage": [ {
        "messageType": "INFO",
        "description": "Found 1 hit in the request."
      } ]
    }
    

    Solution / work around:

    Add the following items to your request should fix the problem. Again at this time it is not documented that they are required. However my testing has shown when you send these everything appears correctly again in the real-time reports.

    cd=ScreenName&an=ApplicationName&aid=ApplicationId&av=3.0&ai‌​id=1.0