We want to use MixPanel to capture events on our site and I'm trying to get hold of the users distinct id, so I'm using the following code snippet:
$(document).ready(function($){
console.log("We have distinct id");
console.log(mixpanel.get_distinct_id());
});
This causes an error saying 'undefined is not a function' when attempting to get the distinct id.
I've checked in the debugger and can confirm that the mixpanel object does not have a get_distinct_id method, However if I wait until the page has loaded and then evaluate mixpanel.get_distinct_id() in the console, I get the distinct id without problem.
I can only guess that the mixpanel object hasn't completed initialisation yet. Is there a callback or an event that I can use to know once the mixpanel object will be able to tell me the users distinct_id?
From a Mixpanel article:
"[...] pass a config object to the mixpanel.init() method with a loaded parameter and a callback function that will execute immediately after our library has finished loading. Inside the callback function, you can use the get_property() and get_distinct_id() methods and ensure that they'll only execute after the library has finished loading."
mixpanel.init('Project Token', {'loaded':function() {
var distinct_id = mixpanel.get_distinct_id()}
});
Source: How to prevent get_distinct_id & get_property from returning undefined
I found a code snippet here: https://gist.github.com/calvinfo/5117821, credit to https://gist.github.com/calvinfo which looks like this:
$(document).ready(function() {
if ($("#mixpanel_distinct_id").length > 0) {
var interval = setInterval(function () {
if (window.mixpanel.get_distinct_id) {
$("#mixpanel_distinct_id").val(window.mixpanel.get_distinct_id());
clearInterval(interval);
}
}, 300);
}
});
Basically this allows you to check every 300 milliseconds whether the mixpanel object has completed initializing and the get_distinct_id function is available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With