Integration guides
Logging data with Javascript
If you want to track things like button clicks, it's easiest to use Ajax. We have a javascript file that you can load located at http://api.mixpanel.com/site_media/js/api/mixpanel.js This is really simple to use and it has no external dependencies.
Setup
To start tracking with Javascript, paste the following code into the page you want to track. Make sure to change 'YOUR_TOKEN' to the project token from your Mixpanel dashboard.
<script type="text/javascript" src="http://api.mixpanel.com/site_media/js/api/mixpanel.js"></script>
<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 };
}
</script>
...
If you want, you can also log from other javascript functions. If you are doing a bunch of javascript, you may want to track each time a user interacts with something:
your_function = function(url, data) {
mpmetrics.track('play-game', {'level':'12', 'weapon':'sword', 'character':'knight'});
if (url) {
some = more_random_js;
} else {
even += "more";
}
...
This will send off an Ajax request each time the function is called, which comes in really handy for javascript-heavy sites.
Tracking navigation
If you try tracking a link with an onclick() event, there won't be enough time for the data to be sent before the page changes. What you can do instead is track the event and then move the page with a callback.
<a href="javascript:void(0);" onclick="mpmetrics.track('click menu', {'menu item': 'about'},
function() { window.location = 'http://yoursite.com'; });">
Advanced notes
If you decide to use a variable that is not mpmetrics when you instantiate MixpanelLib you will also need to pass the object name as well so that our callbacks fire off correctly and leave no errors on your page. This is done very simply:
var newObj = new MixpanelLib("YOUR TOKEN", "newObj");
Javascript Library API
MixpanelLib(token:string)
Initialize a Mixpanel object.
Required:
@token: Your unique project token
Usage:
var mpmetrics = new MixpanelLib('ds098dssll1122k2jd');
mpmetrics.track(event:string, properties:object, callback:function)
Track an event. This is an object method, so you must initialize a
MixpanelLib object before use.
Required:
@event: Name of event
Optional:
@properties: Properties for this event.
@callback: Anonymous function to call after tracking the event.
Example: mpmetrics.track("Open slideshow", {'show': 'Xmas'}, function(){ myfunction() });
mpmetrics.track_funnel(funnel:string, step:int, goal:string, properties:object, callback:function)
Track a funnel step. This is an object method, so you must initialize a
MixpanelLib object before use.
Required:
@funnel: Funnel name, same for all steps of a single funnel
@step: Step number, starting with 1
@goal: Human readable name for this step
Optional:
@properties: Properties for this funnel step.
@callback: Anonymous function to call after tracking the funnel step.
Example: mpmetrics.track_funnel("Signup", 1, "Landing page", {'from': 'Google'});
mpmetrics.register(properties:object, type:string, days:int)
Register a set of super properties, which are included with all events/funnels.
This will overwrite previous super property values. This is an object method, so you must
initialize a MixpanelLib object before use.
Required:
@properties: associative array of properties to store about the user
Optional:
@type: "all", "events", or "funnels". Determines the types of events to
send this data with. Default "all".
@days: Age of cookie in days. The cookie is set frequently so this has little effect.
Default 7.
Example: mpmetrics.register({'user type': 'free trial', 'status': 4}, "all");
mpmetrics.register_once(properties:object, type:string, default_value, days:int)
Register a set of super properties only once. This will not overwrite previous super property
values, unlike register(). However, if default_value is specified, current super properties
with that value will be overwritten.
Required:
@properties: associative array of properties to store about the user
Optional:
@type: "all", "events", or "funnels". Determines the types of events to
send this data with. Default "all".
@default_value: Value to override if already set in super properties (ex "False")
Default "None".
@days: Age of cookie in days. The cookie is set frequently so this has little effect.
Default 7.
Example: mpmetrics.register_once({'user type': 'free trial'}, "all", "False", 31);
mpmetrics.identify(unique_identifier:string)
Identify a user with a unique id. This will not override a user's previous identity,
and so can be safely called multiple times. All subsequent actions caused by this user
will be tied to this identity.
Required:
@unique_identifier: string that uniquely identifies a user
Example: mpmetrics.identify('tim@mixpanel.com');
mpmetrics.set_config(config:object)
Update the tracking object's configuration. Currently the configuration is only used for
cookie handling. Call this before register or register_once if you want to modify how cookies
are handled.
Current config: {
cross_subdomain_cookie: true, // Super properties span subdomains
cookie_name: "mp_super_properties" // Super properties cookie name
}
Required:
@config: new configuration values to update
Example: mpmetrics.set_config({ cross_subdomain_cookie: false });
Logging data with Javascript for Facebook apps
If you are writing iframe apps, you can go ahead and use our normal Javascript library, located at http://api.mixpanel.com/site_media/js/api/mixpanel.js . The integration guide for standard Javascript is located here.
However, if you are using FBML, that library won't work - it doesn't play nice with the Facebook sandbox. We have a separate library, http://api.mixpanel.com/site_media/js/api/mixpanel_fb.js, that works perfectly with Facebook. Usage is exactly the same, and we get all of the data (including IP address) that we do with the normal version.
Setup for FBML apps
To use this javascript library, add a link to it from the page you want to track. Make sure to change 'YOUR_TOKEN' to your project token from the Mixpanel dashboard.
<script type="text/javascript" src="http://api.mixpanel.com/site_media/js/api/mixpanel_fb.js"></script>
<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 };
}
</script>
Then, if you want to track an HTML element you can use mpmetrics.track() as the onclick function:
...
<!-- The rest of your HTML code here -->
<input type="button" onclick="mpmetrics.track('game-start', {'level':'castle', 'char':'knight'})">
If you want, you can also log from other javascript functions. If you are doing a bunch of javascript, you may want to track each time a user interacts with something:
your_function = function(url, data) {
mpmetrics.track('battle', {'spell':'fireball', 'damage':'237'});
if (url) {
some = more_random_js;
} else {
even += "more";
}
...
Each time the mpmetrics.track() event is fired, it will add a transparent pixel to your page. These are set so that there can be a maximum of 100 images loaded at once - once a user has interacted more than 100 times, we remove a pixel before adding a new one. This will ensure that Mixpanel will not cause performance issues on your end, but gives us enough time to log all of your data before the pixel is removed.
Asynchronous Tracking with Javascript
Asynchronous loading decouples tracking from the page loading process in users' web browsers. Delays in downloading Mixpanel's Javascript code will not have any impact on site responsiveness.
Setup
Instead of loading Mixpanel's Javascript code in the normal way using <script> tags, you need to dynamically insert a specially created DOM node. The following code should be inserted at the bottom of the <head> section of your web page. Note that since Javascript downloading is no longer synchronous with respect to page loading, there is no performance penalty for inserting the code early in the page.
<script type="text/javascript">
var mpq = [];
mpq.push(["init", "YOUR TOKEN"]);
(function() {
var mp = document.createElement("script"); mp.type = "text/javascript"; mp.async = true;
mp.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + "//api.mixpanel.com/site_media/js/api/mixpanel.js";
var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(mp, s);
})();
</script>
Note that the mp and s variables above are temporary and are only used for setup. mpq is the only object needed in the rest of the page.
Tracking
Since you can't rely on Mixpanel's code being loaded by the time you want to track events, you have to queue tracking calls rather than making direct calls. In the code from the setup section, you created an mpq object and push your token in an "init" call. That was the equivalent of calling MixpanelLib's constructor. Further tracking calls will follow a similar pattern. Here's an example that should make it clear:
<script type="text/javascript">
mpq.push(["track", "play-game", {"level": "12", "weapon": "sword", "character": "knight"}]);
</script>
The preceding call is equivalent to the track call from the normal Javascript integration guide. In general, everything that can be called using an mpmetrics object, can be called asynchronously by pushing a list onto the mpq object. The first item in the list must be the name of the function to be called, track or funnel for example. The rest of the list will become the arguments to that function.
Technical Details
Initially, mpq is simply a Javascript array. When Mixpanel's library is loaded, two things happen:
- An actual
MixpanelLibobject is created and all previously queued calls are processed. mpq'spushfunction is replaced with a version that no longer actually queues calls. Instead, they are processed immediately.
Logging data with Python
So, you want to log data to Mixpanel from your backend, and your application is written in Python.
You have two options:
1. If you don't have a huge amount of traffic, you can go with the simple python example code located at the code examples page. This is simpler to install and use.
2. If you are worried about performance, we suggest using RabbitMQ, which allows you to efficiently send logs to a workqueue, where they are processed by another program. To learn more about RabbitMQ, please visit Rabbits and warrens.
If you are using the cURL logger from the example code page, first save the code to a file called mixpanel.py. Then, to log data, import the file and call the log function:
# cURL example
import path.to.mixpanel as mpmetrics
...
def some_function(args):
mpmetrics.track("purchase", {"type": "Easter", "item_number": "3123", "ip": "123.78.98.34"})
...
# Now your regular function code
...
If you are using Django, an easy way to grab the user's IP address is through
request.META.get('REMOTE_ADDR').
Logging data with PHP
So, you want to log data to Mixpanel from your backend, and your application is written in PHP.
You have two options:
1. If you don't have a huge amount of traffic, you can go with the simple PHP example code located at the code examples page. This is simpler to install and use.
2. If you are worried about performance, we suggest using RabbitMQ, which allows you to efficiently send logs to a workqueue, where they are processed by another program. To learn more about RabbitMQ, please visit Rabbits and warrens.
If you are using the cURL logger from the example code page, first save the code to a file called logger.php. Then, to log data, import the file, create a new MetricsTracker object and call the track function. You'll notice that it's possible to include the visitor's IP address with the request, which allows us to calculate unique visitors and geolocation data.
<?php
# cURL example
require_once('path/to/logger.php');
$metrics = new MetricsTracker("YOUR_TOKEN");
...
function some_function($args) {
$metrics->track('menu_click', array('button'=>'learn more',
'color'=>'green',
'ip'=>$_SERVER['REMOTE_ADDR'])
);
...
# Now your regular function code
...
}
?>
