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?
So as per the suggestion by @trincot, I added the
$("#distinct_id").val(distinct_id);
to theinit ... loaded
function, and it worked.As a reference, here's what the resulting code looks like:
Additionally, you can skip the
$(document).ready(function() {});
entirely and just do this, as you only need mixpanel to load: