To segment users using the Javascript API, firstly, please follow the first step of the Getting Started article by clicking here


You would also want to refer to our full Javascript API, with detailed description on our API documentation page.


Now, please find below some tips for segmentation of users using the Javascript API.


The specific API call we'll be using is Add Subscriber to a Segment. Here's an example to show you how this API works:


Suppose the user has visited a portion of your site, say the Checkout page, then the visitor (if s/he is a subscriber already), will be added to the segment named “checkout”. For this, you would want to paste the below mentioned code on your website page, after the PushCrew Smart Code before closing </head> tag.




window._pcq = window._pcq || [];
_pcq.push(['APIReady', callbackOnAPIReady]); //will execute callback function when PushCrew API is ready

_pcq.push(['subscriptionSuccessCallback',callbackOnSuccessfulSubscription]); //registers callback function to be called when user gets successfully subscribed

function callbackOnAPIReady() {
 //now api is ready
 _pcq.push(['addSubscriberToSegment', 'checkout', callbackForAddToSegment]);
}

function callbackOnSuccessfulSubscription(subscriberId, values) {
 //user just got subscribed
 _pcq.push(['addSubscriberToSegment', 'checkout', callbackForAddToSegment]);
}

function callbackForAddToSegment(response) {
 if(response === -1) {
 console.log('User is not a subscriber or has blocked notifications');
 }
 
 if(response === false) {
 console.log('Segment name provided is not valid. Maximum length of segment name can be 30 chars and it can only contain alphanumeric characters, underscore and dash.');
 }
 
 if(response === true) {
 console.log('User got added to the segment successfully. Now you may run any code you wish to execute after user gets added to segment successfully');
 }
}




PLEASE NOTE: Once the above task is performed, you do not need to manually create the “checkout” segment as it will be automatically created for the very first time the user visits this page.


You can now send notifications to this segment directly from the dashboard by going to Send New Notification button --> Send to --> Segment. In the image below, we have chosen the segment "House Stark".


UtrRSB2wlRHKMdTlf1wbjMVirFNQna0gOw.png



You can also Segment users using Google Tag Manager.