Getting Logged In User - Javascript for Piwik

Solved General Discussion
  • @baris Got it! Thank you. So much to learn about javascript. Now I am off to figure out why I am not seeing the user id being reported in Piwik. As an aside I had tried the suggestion you made a few days ago but without seeing a noticeable change in the Piwik reporting and not seeing the user id in the html page source I thought I had setup the line incorrectly.

  • Strange, strange, strange. When I look at the browser console log I do see the "user id is 1' entry. (Yes, my user id on my forum is #1 -- my account was first.) But yet Piwik still does not see the number 1. If I put app.user.uid in single quotes then Piwik sees myself as user "app.user.uid". So, some thing is happening in the _paq.push(['setUserId', app.user.uid]); line such that even though the console is showing user 1 it is still not being parsed by Piwik.

    Sooo frustrating.

  • Have you tried sending in parseInt(app.user.uid, 10) instead?

  • @julian The dense must be strong with me. 馃槥 I can't make this work. It seems that the app.user.uid object isn't being converted to the number when it is sent off in the _paq.push(...) command.

  • FIXED!

    This is what works:

    _paq.push(['setUserId', ''+app.user.uid+'']);

    Two single quotes and the plus symbol!

    Geez, it feels like I just gave birth!

    Now to learn how to do an if then statement in javascript. I want to only include that line if the user is logged in, ie., the app.user.uid value is not zero.

  • Actually app.user.uid is already a number so try converting it to a string. _paq.push(['setUserId', app.user.uid.toString()]);

  • @baris Excellent! That works also. I will leave it as you suggested.

  • @rod

    if (app.user && app.user.uid > 0) {
      _paq.push(['setUserId', app.user.uid.toString()]);
  • @julian Thank you. Your suggestion is more elegant than mine was. I hadn't even thought of also checking for "app.user" and was only looking for a non zero to app.user.uid.

  • @rod It's nothing special, it's just a habit that I have trained myself into.

    The reason I check for the existence of app.user is because you cannot reference an object property (that is, the uid property of the user object in app) if the object itself does not exist. You'll get a javascript error (ReferenceError: user is not defined).

    If there's even a chance the parent object is not defined, I make a check for it first (though app is always defined in NodeBB, so I skip that).

    The proper way to write it would be: if (app.hasOwnProperty('user')), but even sometimes that can be tripped up if app.user is a property, but undefined 馃槃

Suggested Topics