Code examples

Javascript example using jsonp

This Javascript snippet will work for logging user actions from the frontend for standard webapps. For Facebook apps, see our Facebook guide.

<!-- First include the script: -->
<script type="text/javascript">
var mp_protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
document.write(unescape("%3Cscript src='" + mp_protocol + "api.mixpanel.com/site_media/js/api/mixpanel.js' type='text/javascript'%3E%3C/script%3E"));
</script>

<!-- Initialize it with your project token -->
<script type="text/javascript">
try {
    var mpmetrics = new MixpanelLib("YOUR_TOKEN");
} catch(err) {
    null_fn = function () {};
    var mpmetrics = { 
        track: null_fn, 
        track_funnel: null_fn, 
        register: null_fn, 
        register_once: null_fn,
        register_funnel: null_fn,
        identify: null_fn
    };
}
</script>

<!-- Then make calls to our API as shown below: -->
<script type="text/javascript">
mpmetrics.track('click-menu', {'gender':'male', 'button':'about'});
</script>

Additionally, you can call our Javascript API in a Flash SWF, please visit http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_15683 for an example. If you would like to browse the uncompressed source, check out http://api.mixpanel.com/site_media/js/api/mixpanel_dev.js

PHP non-blocking example

<?php
/*
If you wish to do metric logging from your backend, the best method of doing this is 
to do it in a non-blocking way. This will let your pages continue to execute at
about the same speed  while logging metric data in the background. Please note: If 
you're on a shared host, you may be limited in logging metric data with a background 
process.

Feel free to modify this code to your own environments liking
*/
class MetricsTracker {
    public $token;
    public $host = 'http://api.mixpanel.com/';
    public function __construct($token_string) {
        $this->token = $token_string;
    }
    function track($event, $properties=array()) {
        $params = array(
            'event' => $event,
            'properties' => $properties
            );

        if (!isset($params['properties']['token'])){
            $params['properties']['token'] = $this->token;
        }
        $url = $this->host . 'track/?data=' . base64_encode(json_encode($params));
        //you still need to run as a background process
        exec("curl '" . $url . "' >/dev/null 2>&1 &"); 
    }

    function track_funnel($funnel, $step, $goal, $properties=array()) {
        $properties['funnel'] = $funnel;
        $properties['step'] = $step;
        $properties['goal'] = $goal;
        $this->track('mp_funnel', $properties);
    }
}

// Example usage:
$metrics = new MetricsTracker("YOUR_TOKEN");
$metrics->track('purchase', 
                    array('item'=>'candy', 'type'=>'snack', 'ip'=>'123.123.123.123'));
// You MUST include a distinct_id OR an IP address to track funnels from the backend
$metrics->track_funnel('Signup', 1, 'hit landing page',
                        array('distinct_id' => 'USER_ID', 'ip'=>'123.123.123.123'));
?>

Python non-blocking example

# This isn't perfect for high traffic sites, if you need something more production ready
# please tell us or stay tuned as we will open it up shortly.

import subprocess
import base64
import simplejson

def track(event, properties=None):
    """
    A simple function for asynchronously logging to the mixpanel.com API.
    This function requires `curl` and Python version 2.4 or higher.
    
    @param event: The overall event/category you would like to log this data under
    @param properties: A dictionary of key-value pairs that describe the event
                       See http://mixpanel.com/api/ for further detail.
    @return Instance of L{subprocess.Popen}
    """
    if properties == None:
        properties = {}
    token = "YOUR_TOKEN_HERE"
    if "token" not in properties:
        properties["token"] = token

    params = {"event": event, "properties": properties}
    data = base64.b64encode(simplejson.dumps(params))
    request = "http://api.mixpanel.com/track/?data=" + data
    return subprocess.Popen(("curl",request), stderr=subprocess.PIPE,
        stdout=subprocess.PIPE)

def track_funnel(funnel, step, goal, properties=None):
    if properties == None:
        properties = {}
    properties["funnel"] = funnel
    properties["step"] = step
    properties["goal"] = goal
    track("mp_funnel", properties)

# Example usage:
track("invite-friends", 
             {"method": "email", "number-friends": "12", "ip": "123.123.123.123"})

# You MUST include a 'distinct_id' OR 'ip' property to use the funnel
track_funnel("signup funnel", 1, "landing page", 
             {"distinct_id": "USER_ID", "referer": "campaign 1"})

Ruby non-blocking example

require 'rubygems'
require 'base64'
require 'json'
require 'active_support'

class MixPanel

  # A simple function for asynchronously logging to the mixpanel.com API.
  # This function requires `curl`.
  #
  # event: The overall event/category you would like to log this data under
  # properties: A hash of key-value pairs that describe the event. Must include 
  # the Mixpanel API token as 'token'
  #
  # See http://mixpanel.com/api/ for further detail.
  def self.track(event, properties={})
      if !properties.has_key?("token")
        raise "Token is required"
      end

    params = {"event" => event, "properties" => properties}
    data = ActiveSupport::Base64.encode64s(JSON.generate(params))
    request = "http://api.mixpanel.com/track/?data=#{data}"

    `curl -s '#{request}' &`
  end

  def self.track_funnel(funnel, step, goal, properties={})
    properties["funnel"] = funnel
    properties["step"] = step
    properties["goal"] = goal
    track("mp_funnel", properties)
  end