Mixpanel Javascript - distinct_id variable returning an object

350 views Asked by At

I'm trying to set up Mixpanel People tracking on my registration form, but I'm unable to pass Mixpanel's distinct_id to my form.

This is the script that gets the user's distinct_id from Mixpanel (documentation):

mixpanel.init("MY_TOKEN", {
    loaded: function(mixpanel) {
        distinct_id = mixpanel.get_distinct_id();
    }
});

When I try to pass it to a hidden input in my registration form with

$(document).ready(function(){
    $("#distinct_id").val(distinct_id);
});

to <input type="hidden" name="distinct_id" id="distinct_id" value="" />, the resulting line in the source code in Chrome Inspector just looks like this: <input type="hidden" name="distinct_id" id="distinct_id" value="[object HTMLInputElement]">

Yet, when I do console.log(distinct_id); in the Chrome console, it outputs the ID.

I'll admit that my javascript is pretty rubbish, so I could be missing something obvious here... I've tried parsing it with the JSON.stringify function like so:

$(document).ready(function(){
    distinct_id = JSON.stringify(distinct_id, null, 4);
    $("#distinct_id").val(distinct_id);
});

but it just produced {} as a value in the form...

Any suggestions?

2

There are 2 answers

0
tristanojbacon On

So as per the suggestion by @trincot, I added the $("#distinct_id").val(distinct_id); to the init ... loaded function, and it worked.

As a reference, here's what the resulting code looks like:

mixpanel.init("MY_TOKEN", {
    loaded: function(mixpanel) {
        distinct_id = mixpanel.get_distinct_id();
        $(document).ready(function(){
            $("#distinct_id").val(distinct_id);
        });
    }
});

Additionally, you can skip the $(document).ready(function() {}); entirely and just do this, as you only need mixpanel to load:

mixpanel.init("MY_TOKEN", {
    loaded: function(mixpanel) {
        distinct_id = mixpanel.get_distinct_id();
        $("#distinct_id").val(distinct_id);
    }
});
0
Bowen Beyer-Johnson On

Based on what you have shared it looks likes right now you are treating the variable "distinct_id" as a global variable when it is actually only within the scope of the init function. As trincot mentioned, moving what you have in the $(document).ready() block might solve the issue, though declaring distinct_id as a global variable should also work.