Fortunately, the KISSmetrics Javascript API allows you do most of the work for an A/B experiment with one call to KM.ab. Check our APIs section for more details on which APIs support which features. Below constitutes a complete A/B test:
A few things to note:
<!--
Here is our signup button. Notice that it is hidden by
setting the style to "display: none". Also notice that
it is by default using the "green" image.
-->
<img src="/images/green.png" id="signup_button" style="display: none"/>
<script>
// If for some reason KISSmetrics doesn't load or there is an
// error we'll just show the default green button after 1.5s
var abTimeout1 = setTimeout(function(){
document.getElementById("signup_button").style.display = '';
}, 1500);
// Now we need to add some Javascript code to run our A/B test
// Using _kmq.push to call our setup function ensures that it
// is only called once KM is loaded
_kmq.push(function(){
// Set up the experiment (this is the meat and potatoes)
var color = KM.ab("Signup Button Color", ["red", "green"]);
// Set the button color
var button = document.getElementById("signup_button");
button.src = "/images/"+color+".png"; // Set the button color
button.style.display = ''; // Show the button
// Clear the timeout, since this worked fine
clearTimeout(abTimeout1);
});
// Record when someone clicks on the button
_kmq.push(["trackClick", "signup_button", "Clicked Signup"])
</script>
KM.ab without going through _kmq you risk exposing your users to Javascript errors.KM.ab to set the src attribute of our image. If the variants you were testing were more complicated you might have both variants in HTML, as two separate elements on the page (with both hidden) and then just show the appropriate variant when you get the selected variant from KM.ab.KM.ab does several things. It: