blankip
blankip

Reputation: 340

How do I report on a session variable in google analytics?

I am new to custom variables in google analytics. I don't understand how to grab session/post variables from a user.

I am trying to capture $_SESSION['usercountry'] and add it to the GA data. It simply displays the country from which a user is signed up.

From the GA

_gaq.push(['_setCustomVar',
      2,                   // This custom var is set to slot #2.  Required parameter.
      'Country', // The name of the custom variable.  Required parameter.
      '???',               // The value of the custom variable.  Required parameter.
                           //  (you might set this value by default to No)
      2                    // Sets the scope to session-level.  Optional parameter.
]);

Do I just put in usercountry in where I have the question marks?

Upvotes: 1

Views: 409

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123513

Client-side JavaScript doesn't have access to $_SESSION, as the collection is kept server-side.

You'll need to expose the value to JavaScript somehow. One option is to simply include it in the initial output from PHP:

<script>
    var userCountry = <? echo json_encode($_SESSION['usercountry']) $>;
</script>

This uses json_encode() and takes advantage of JSON's relation and shared syntax with JavaScript, so it'll be parsed as a JavaScript literal. Presumably a String, so the result from the PHP echo would be similar to:

<script>
    var userCountry = "Country Name";
</script>

Then, you can use it for Google Analytics:

_gaq.push([
    '_setCustomVar',
    2,                 // This custom var is set to slot #2.  Required parameter.
    'Country',         // The name of the custom variable.  Required parameter.
    userCountry ,      // The value of the custom variable.  Required parameter.
                       //  (you might set this value by default to No)
    2                  // Sets the scope to session-level.  Optional parameter.
]);

Upvotes: 1

Related Questions