Search code examples
javascriptvariablesasynchronouspushmatomo

How to insert data from async call into push method


I am user of https://github.com/jackspirou/clientjs. It creates fingerprint of user visiting my site. I am also user of Piwik, open source analytic tool. I'm trying to implement one of its feature - http://developer.piwik.org/guides/tracking-javascript-guide#user-id.

My code looks like:

var client = new ClientJS();
var fingerprint = client.getFingerprint();

var _paq = _paq || [];
_paq.push(['setUserId', fingerprint]);
_paq.push(['trackPageView']);

And it does not work. Data inserted by code above into my database are "NULL" for UserID field. It is probably the problem with getFingerprint() being asynchronous. My question is - how to bypass it?


Solution

  • You have to look at the client.getFingerprint() documentation. Most likely it's something like this:

    client.getFingerprint(function(result, err) {
        // check for err
        // do something with result
        var _paq = _paq || [];
        _paq.push(['setUserId', result]);
        _paq.push(['trackPageView']);
    });
    

    Note, I'm only guessing the returning data as result and err, but it could be on object. Also, I'm guessing it accepts the callback function as one single parameter.