getVisitorId() with asynchronous javascript


#1

Hi! I know this is probably a really basic question, but I am relatively new to Piwik and need to access the visitor ID so I can pass it in a form on my page. The rest of the tracking is working fine with this code. I am using the default code provided by my piwik control panel:


<!-- Piwik -->
	<script type="text/javascript">
	  var _paq = _paq || [];
	  _paq.push(["trackPageView"]);
	  _paq.push(["enableLinkTracking"]);

	  (function() {
		var u=(("https:" == document.location.protocol) ? "https" : "http") + "://12a-gisr.com/analytics/";
		_paq.push(["setTrackerUrl", u+"piwik.php"]);
		_paq.push(["setSiteId", "1"]);
		var d=document, g=d.createElement("script"), s=d.getElementsByTagName("script")[0]; g.type="text/javascript";
		g.defer=true; g.async=true; g.src=u+"piwik.js"; s.parentNode.insertBefore(g,s);
	  })();
	</script>
	<noscript><img src="http://12a-gisr.com/analytics/piwik.php?idsite=1&rec=1" style="border:0" alt="" /></noscript>
<!-- End Piwik Code -->

How would I go about getting the visitor ID piwik has assigned to the user?

I have tried this:


<script>
	$(window).load(function(){ 
	alert(piwikTracker.getVisitorId());
	});
</script>

But it doesn’t appear to be working. Any ideas? Thanks!


(Matthieu Aubry) #2

See on the user guide: JavaScript Tracking Client: API Reference - Matomo Analytics (formerly Piwik Analytics) - Developer Docs - v3

For example:

var visitor_id;
_paq.push([ function() { visitor_id = this.getVisitorId(); }]);

or for example, to fetch a custom variable (name,value) using the asynchronous code:

_paq.push([‘setCustomVariable’,‘1’,‘VisitorType’,‘Member’]);
_paq.push([ function() { var customVariable = this.getCustomVariable(1); }]);

You can push to the _paq array even after the piwik.js file has been loaded and run.