Using the Surveys API

Product Fruits Surveys work without using the JavaScript API. For example, NPS can be deployed immediately and you can start getting data from your users. In some scenarios, however, you might want to trigger different actions based on certain answers. This is where you can leverage the JS API for Surveys.  

As an example, if a user creates a new account, you might want to ask for data that you can later use to deliver a personalized experience. You can ask for the job position of a user and change the application experience accordingly. In this article, we will create a simple Welcome survey and JavaScript code to handle the scenario.

Create a survey

Create a new survey and place a new Single choice question in it. Ask the user about their job position. 

e.g.:

We will be launching the survey manually via JS code because we want to have more control. However, this is not a required step. Scroll down and select the Manual trigger.

Getting IDs for use with the JavaScript API

When you switch to the Manual trigger, you can open a page with developer information. This page shows you all the possible IDs you need for working with responses.

On the developer info page, you will see IDs of questions or choices (if there are choice type questions available).

Writing the JavaScript code

First, because we're using the manual trigger, let's start the survey from the code. It is a simple JS method call and it is up to you when to launch it. In our example, it should be immediately after the user is registered.

You'll need a survey ID for this, which you will find on the screen described in the previous section.

window.productFruits.api.surveys.startSurvey('XXX-XXX-XXX-XXX')

Now the survey will load. Register a callback for the survey-closed event to be notified when the survey is closed or finished:

window.productFruits.api.surveys.listen('survey-closed', (e) => {
	// this will be called when the survey is closed/finished by the user
});

The last step is to read the answers. You need to know the question and its choice IDs. Again, you will find this on the developer info page.

window.productFruits.api.surveys.listen('survey-closed', (e) => {
    if (e.surveyId == 'XXX-XXX-XXX-XXX') {
        const answers = e.answers;
        
		const jobPosAnswer = answers.find(a => a.questionId == 'QUESTION-ID');
		
		if (jobPosAnswer) { // it can be undefined if the question was not answered by the user
			/*
				You can now read the answer. In our case, this will be an array
				of strings where the string is an ID of the selected choice.
				
				You can call anything in your code based on the values.
			*/
			
			console.log(jobPosAnswer.answer);
		}
    }
});

And that's it!