10

I'm using the Javascript API for Google Analytics Content Experiments and it seems like you have two choices:

  1. Run one experiment at a time and have Google assign the variation, which you can get using chooseVariation(), or
  2. Run several experiments at a time and assign the variation yourself using setChosenVariation()

(1) lets Google control the number of users assigned to each variation, which I need, but I have several experiments. This seems pretty basic. What am I missing?

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144
  • Are you trying to achieve anything in particular ? Or just curious about what is possible using the GA Content Experiment JS API ? – nt_1 May 08 '13 at 14:13
  • @nt_1 My boss has a dozen experiments he wants to run, many simultaneously. It'd be better if we could control those experiments from GA. – Michael Lorton May 08 '13 at 16:18

4 Answers4

19

I don't think you're missing anything. My understanding is that the GA Experiments API allows you to allocate a visitor to any version of a single A/B/N test with the Choose Variation command :

cxApi.chooseVariation();

However, this function is only available if you specify the experiment ID when loading the api.js on the page.

If what you want to do is to run several A/B tests on one page at the same time, this is really multi-variate testing and unfortunately this is not available 'out-of-the-box' in GA Content Experiments (it used to be available with Google Website Optimizer). You can still 'fake' it using your own bucketing, with code like :

<!-- 1. Load the Content Experiments JavaScript Client -->
<script src="//www.google-analytics.com/cx/api.js"></script>

<!-- 2. See if the visitor has seen an experiment already -->
<script>
// loop through all active experiments server-side. 
cxApi.getChosenVariation(
 $experimentId
 );

<!-- 3. Bucket the visitor if he isn't bucketed already -->
// loop through your live experiments 
  cxApi.setChosenVariation(
    $chosenVariation,             // The index of the variation shown to the visitor
    $experimentId                 // The id of the experiment the user has been exposed to
  );
</script>

You will need to decide whether you want a visitor to only view one experiment at a time or enter multiple experiments concurrently.

The first option is probably more reliable but means you will have to split your visitor in quite a lot of buckets, meaning your tests will take a long time before returning a result.

If you use the second option, you need to be careful : if your experiments are not independent, you won't be able to trust the test results from Google Analytics, as the statistical tests used in the Content Experiments assume independence. Even if your experiments are independent, you'll need to have an equal split among all variation combinations.

I hope that helps !

nt_1
  • 703
  • 4
  • 8
  • 1
    Thank you, it's exactly what I *am* doing, but I felt foolish because it seemed like I was re-inventing the wheel. We have been doing a crude multi-variate testing: assigning equal splits at random, and only testing (apparently) unrelated parts of the UI. – Michael Lorton May 14 '13 at 22:35
  • 1
    Could someone provide a complete example of the code that should be used? I guess the code provided by nt_1 is just for orientation, but should be completed/modified to make it work, right? I asked about this in a separate question (http://stackoverflow.com/questions/23524229/run-multiple-simultaneous-tests-with-google-content-experiments-api) with no answers so far. – migueltic Aug 17 '14 at 10:18
  • But how do you set the `$chosenVariation` in `setChosenVariation()` if you don't know the total number of available variations to choose from? – Jake Wilson Jun 06 '16 at 18:56
2

when running many simultaneously experiments the problem is that if you have visitors from one experiment that interact with elements of another experiment running on your site then it is difficult to account for these interactive effects. This will skew your data and lead to some faulty conclusions.if you’re absolutely confident in how to analyze multiple concurrent experiments, it’s okay be safe and run one experiment at a time.

2

I solved this using a node.js script.

Out-of-the-box Google Content Experiments makes you choose between:

  • Load cxApi patched only for 1 experiment
  • Load cxApi plain, and lose the ability to call chooseVariation() function, making you implement your own choosing algorithm (which is a shame, as google's multi-armed bandit idea is really smart).

So I did some reverse engineering on how google cxApi js is patched for 1 experiment, it turns it out it just bundles the experiment info (the variations weights) in the middle of the file, I experimented touching the bundle manually adding multiple experiments, and now I can call cxApi.chooseVariation(experimentId) for each experiment, and works nicely!

Weights change every 12hs, so I automated it, I created a node.js little app that will download cxApi from google, and then repeatedly download it for each experiment you specify, and patch a cxApi with all your experiments on it.

Voila!, multiple experiments on any page.

Here's the repo: https://github.com/benjamine/mutagen, fork at will

this node.js app will patch cxApi for multiple experiments, and will also pack (and minify) your variations

Daniel Werner
  • 1,350
  • 16
  • 26
Benja
  • 4,099
  • 1
  • 30
  • 31
2

This solution works very well for me. The benefits are:

  • no node.js required
  • no changes to site needed - site remains fully cacheable
  • Google Multi-Armed-Bandit approach used, no patch
  • easily maintainable

Javascript Module providing all functionality for executing multiple Google Experiments:

var runExperiment = (function(jQ) {

    var apiUrl = '/ga-experiments-api.php?preview=true&experimentId=',
        experimentId,
        variations;

    var chooseAndApplyNewVariation = function() {
        if (typeof jQ !== 'undefined') {
          jQ.ajax({
              type: 'get',
              url: apiUrl + experimentId,
              success: function(data, status){
                  var choosenVariation = data.choosenVariation;

                  if (typeof choosenVariation !== 'undefined' && choosenVariation >= 0) {
                      cxApi.setChosenVariation(choosenVariation, experimentId);
                      applyVariation(choosenVariation);
                  }
              }
          });
        }  
    };

    var applyVariation = function(chosenVariation) {
        var variationFunction = (typeof variations[chosenVariation] === 'function') ? variations[chosenVariation] : false;

        if (variationFunction) {

            variationFunction.apply();
            sentGaEvent();
            console.log(experimentId, chosenVariation);
        }
    };

    var sentGaEvent = function() {
        if (typeof ga !== 'undefined') {
            ga('send', 'event', 'experiment', 'view');
        }
    };

    return function(experiment) {
        experimentId = experiment.id;
        variations = experiment.variations;

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

            var chosenVariation = cxApi.getChosenVariation(experimentId);

            if (chosenVariation >= 0) {

                applyVariation(chosenVariation);

            } else {

                chooseAndApplyNewVariation();
            }
        }
    };
})(jQuery);

Javascript Snippet for running single experiment - can be integrated multiple times on page:

(function(jQ) {
    var experiment = {
        'id': 'RHwa-te2T_WnsuZ_L_VQBw',
        'variations': [
            function() {},
            function() {
                jQ('#nav #menu-item-2000927 a').text('Shop + Abo');
            }]
    };

    runExperiment(experiment);
}(jQuery));

PHP (API) for generating new variations through Google's API, I used this class:

https://github.com/thomasbachem/php-gacx

<?php

use UnitedPrototype\GoogleAnalytics;

require_once dirname(__FILE__) . '/libs/googleAnalytics/Experiment.php';

$experimentId = (!empty($_GET['experimentId'])) ? $_GET['experimentId'] : null;

$returnData = array(
    'experimentId' => $experimentId,
);

try {
    $experiment = new GoogleAnalytics\Experiment($experimentId);

    $variation = $experiment->chooseNewVariation();

    if (is_integer($variation)) {

        $returnData['success'] = true;
        $returnData['choosenVariation'] = $variation;
    }

} catch (Exception $exception) {

    $returnData['success'] = false;
    $returnData['error'] = $exception;
}

header('Content-Type: application/json');

echo json_encode($returnData);
Daniel Werner
  • 1,350
  • 16
  • 26
HKandulla
  • 1,101
  • 12
  • 17
  • HKandulla, could you please provide some explanation (how to use it, where to put each code, what elements of the code should be changed/personalized for each website or test...), not just the code snippets? If you want to, you can also include it as an answer to my question http://stackoverflow.com/questions/23524229/run-multiple-simultaneous-tests-with-google-content-experiments-api Thanks! – migueltic Aug 17 '14 at 10:32
  • 1
    Hi Migueltic, sorry for my late reply. The **PHP-code** goes into a single PHP-File (ga-experiments-api.php) somewhere accessible in your documentRoot - this functions as an api and the Javascript calls this file throught ajax. The **Javascript Module** needs to be included in your html-file (head!) after you included **www.google-analytics.com/cx/api.js**. The **Javascript Snippet** can go anywhere after you included the **Javascript Module**. – HKandulla Sep 03 '14 at 09:59
  • Hope that helps. if not let me know! – HKandulla Sep 03 '14 at 10:00
  • Thanks HKandulla, I think I understand it much better now. We also need to upload the php-gacx file to /libs/googleAnalytics/Experiment.php, right? And the only thing we have to change of all that code is the Javascript Snippet with the ID of each test and the Jquery changes we want to make for the test, right? – migueltic Sep 04 '14 at 13:59
  • Yes, upload this class https://github.com/thomasbachem/php-gacx and include it in your own API (PHP-Script as above) - I called it ga-experiments-api.php. You API should than be working when you call it like this /ga-experiments-api.php?experimentId in the browser. The experimentId needs to be valid. – HKandulla Sep 08 '14 at 14:24
  • I think I've followed the steps correctly, but it's not working at all for me (the test variations are never shown and GA is not registering any sessions in the experiments dashboard). Could you take a quick look to the source code of my site (http://www.efetic.com/) in case you can see what I'm doing wrong, please? Thanks again! – migueltic Sep 23 '14 at 20:27
  • I had a look at your site. The ga-experiments-api.php is not correctlty connecting to GA. I returns: { "experimentId": "nKELe64ZRXKgv7umRLN11Q", "success": false, "error": { } }. Unfortunately, the "$returnData['error'] = $exception;" is not returning the actual Exception, so I cannot see what the actual problem is. You need to debug the PHP-Script - just call it through this URL: /ga-experiments-api.php?experimentId=nKELe64ZRXKgv7umRLN11Q and output/debug the to variables ($experiment, $variation) inside the Try-Clause. This should give you an idea where the problem is created. – HKandulla Sep 29 '14 at 09:02
  • I've discovered what was causing the error (Curl was not installed in my server). Now that's solved, but it's still not showing the variations and GA is not registering anything in the experiments dashboard. I don't know if it is related, but when I reload /ga-experiments-api.php?experimentId=nKELe64ZRXKgv7umRLN11Q it shows a different "choosenVariation" each time (like if it's randomly assigned every time the page loads). That shouldn't work like that, right? Any clue on what's the underlying problem? – migueltic Oct 01 '14 at 14:51
  • I think you are nearly there! The Api seems to be working fine. The reason you are not seeing anything ist that inside the ajax.success var choosenVariation = data.choosenVariation; is returning 'undefined'. I think this is because you jQuery is too old (1.12). Could you please update your jQuery and let me know when it's done. – HKandulla Oct 02 '14 at 11:06
  • I've updated Jquery to 1.7.1. Now it's showing the variations, but not working OK: When I reload it changes the variation shown and I think it's only showing the variation of the test whose code appears below (I was only seeing the variation of one test, changed the order of the test scripts and then the other test started showing and the first one stopped showing). There is no data in GA panels (I've waited like 15 hours) and it's still showing a different "choosenVariation" each time I reload /ga-experiments-api.php?experimentId=nKELe64ZRXKgv7umRLN11Q Thanks for your patience, HKandulla! – migueltic Oct 03 '14 at 07:42