Skip to content

Instantly share code, notes, and snippets.

@ak--47
Created July 19, 2020 14:12
Show Gist options
  • Save ak--47/2dac48e56f3ee44502cb6a42e00c0821 to your computer and use it in GitHub Desktop.
Save ak--47/2dac48e56f3ee44502cb6a42e00c0821 to your computer and use it in GitHub Desktop.
Mixpanel .track() with no dependencies
//a vanilla implementation of .track()
//docs: https://developer.mixpanel.com/docs/http
//by AK
function trackStuff(uuid, eventName, props, token) {
//the mixpanel data model
let spec = {
"event": eventName,
"properties": {
// these two properties are required!
"distinct_id": uuid,
"token": token
}
};
//iterate through props
if (props) {
for (prop in props) {
//append them to our spec
spec.properties[prop] = props[prop];
}
}
// base64 encode
let payload = btoa(JSON.stringify(spec));
//make a vanilla HTTP request as per: https://developer.mixpanel.com/docs/http#section-tracking-events
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
console.log("data sent");
}
};
xhttp.open("GET", "https://api.mixpanel.com/track/?data=" + payload + "&ip=1", true);
xhttp.send();
}
// how we might use this
let someProps = {
"user type": "maverick",
"interests": ["foo", "bar", "baz", "qux"]
};
trackStuff("ak!", "App Open", someProps, "009c696fd3f040f5b32297ac50845210");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment