API Reference

Making Requests from Quiz and Saving Data

This guide explains how to make HTTP requests from a quiz and save the response data using w2w.set().

Step 1: Add JS Code Block

  1. Open your quiz in the editor
  2. Select the screen where you want to add the code
  3. Click the + button next to "Blocks"
  4. Select JS Code from the block menu
  5. The JS Code block will be added to your screen

Step 2: Write Your Request Code

In the JS Code block's content field, write your JavaScript code to make the request. Here's a basic example:

// Get properties from previous quiz answers or saved data
const userId = w2w.get('user_id', '');
const userEmail = w2w.get('email', '');
const quizAnswers = w2w.get('quiz_answers', '{}');

// Make a fetch request with parameters from w2w.get()
const apiUrl = 'https://api.example.com/data?user_id=' + encodeURIComponent(userId);
fetch(apiUrl, {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'X-User-Email': userEmail
    }
})
.then(response => response.json())
.then(data => {
    // Save the data using w2w.set()
    w2w.set('api_response', JSON.stringify(data));
    
    // Or save individual properties
    if (data.user) {
        w2w.set('user_name', data.user.name);
        w2w.set('user_email', data.user.email);
    }
})
.catch(error => {
    console.error('Request failed:', error);
    w2w.showToast('Failed to fetch data', 'error');
});

Step 3: Using POST Requests

For POST requests with data retrieved using w2w.get():

// Get multiple properties to send in the request
const userId = window.user_id;
const userName = w2w.get('name', '');
const userEmail = w2w.get('email', '');
const quizAnswers = w2w.get('quiz_answer', 'default_answer');
const userCountry = w2w.get('user_country_code', '');
const authToken = w2w.get('auth_token', '');

// Parse quiz answers if it's a JSON string
let answers = {};
try {
    answers = typeof quizAnswers === 'string' ? JSON.parse(quizAnswers) : quizAnswers;
} catch (e) {
    answers = {};
}

fetch('https://api.example.com/submit', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + authToken
    },
    body: JSON.stringify({
        user_id: userId,
        name: userName,
        email: userEmail,
        quiz_id: window.quiz_id,
        answers: answers,
        country: userCountry,
        timestamp: new Date().toISOString()
    })
})
.then(response => response.json())
.then(data => {
    // Save response data
    w2w.set('submission_id', data.id);
    w2w.set('submission_status', data.status);
    
    // Optional: show success message
    w2w.showToast('Data saved successfully!', 'success');
})
.catch(error => {
    console.error('Error:', error);
});

Step 4: Using w2w.set() to Save Data

The w2w.set() method saves data to user properties:

Syntax:

w2w.set(key, value, callback)

Parameters:

  • key (string): The property name to save
  • value (any): The value to save (strings, numbers, objects, etc.)
  • callback (function, optional): Function to execute after saving

Examples:

// Save a simple string
w2w.set('user_preference', 'dark_mode');

// Save a number
w2w.set('score', 95);

// Save with callback
w2w.set('api_token', 'abc123', function() {
    console.log('Token saved!');
    w2w.moveToNextScreen();
});

Complete Example

Here's a complete example that retrieves properties using w2w.get(), makes a request, and saves the response:

// Step 1: Get all needed properties from previous quiz answers or saved data
const userId = w2w.get('user_id', '');
const userEmail = w2w.get('email', '');
const authToken = w2w.get('auth_token', '');
const userCountry = w2w.get('country', '');

// Step 2: Build request URL with query parameters from properties
const baseUrl = 'https://api.example.com/user/profile';
const queryParams = new URLSearchParams({
    user_id: userId,
    country: userCountry
});
const apiUrl = baseUrl + '?' + queryParams.toString();

// Step 3: Fetch user profile data using retrieved properties
fetch(apiUrl, {
    method: 'GET',
    headers: {
        'Authorization': 'Bearer ' + authToken,
        'X-User-Email': userEmail,
        'Content-Type': 'application/json'
    }
})
.then(response => {
    if (!response.ok) {
        throw new Error('Network response was not ok');
    }
    return response.json();
})
.then(userData => {
    // Step 4: Save multiple properties from the response
    w2w.set('user_name', userData.name);
    w2w.set('user_email', userData.email);
    w2w.set('user_plan', userData.subscription_plan);
    w2w.set('user_profile', JSON.stringify(userData));
    
    // Step 5: Use saved properties for next request
    const updatedProfile = {
        ...userData,
        last_updated: new Date().toISOString()
    };
    
    // Show success notification
    w2w.showToast('Profile loaded successfully!', 'success', 3);
    
    // Optional: move to next screen after saving
    setTimeout(() => {
        w2w.moveToNextScreen();
    }, 1000);
})
.catch(error => {
    console.error('Error fetching profile:', error);
    w2w.set('api_error', error.message);
    w2w.showToast('Failed to load profile', 'error');
});

Example: Using Properties in URL Parameters

Here's an example showing how to use w2w.get() properties in URL parameters:

// Get properties
const userId = w2w.get('user_id', '');
const sessionId = w2w.get('session_id', '');
const productId = w2w.get('product_id', '');

// Build URL with query parameters
const url = `https://api.example.com/products/${productId}/recommendations?user_id=${encodeURIComponent(userId)}&session=${encodeURIComponent(sessionId)}`;

fetch(url, {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
    }
})
.then(response => response.json())
.then(recommendations => {
    // Save recommendations
    w2w.set('recommendations', JSON.stringify(recommendations));
    w2w.set('recommendations_count', recommendations.length);
})
.catch(error => {
    console.error('Error:', error);
});

Notes

  • The JS Code block executes after a timeout (default: 100ms). You can adjust this in the block properties.
  • Data saved with w2w.set() is accessible later using w2w.get(key).
  • Saved properties persist across screens and can be used in conditional logic.
  • Use w2w.setUserProperties() to save multiple properties at once for better performance.

Using w2w.get() to Retrieve Properties

The w2w.get() method retrieves previously saved data:

Syntax:

w2w.get(key, defaultValue)

Parameters:

  • key (string): The property name to retrieve
  • defaultValue (any, optional): Default value if property doesn't exist

Examples:

// Get a property with default value
const userId = w2w.get('user_id', '');
const email = w2w.get('email', '[email protected]');

// Get a number with default
const score = w2w.get('score', 0);

// Get JSON string and parse it
const answers = JSON.parse(w2w.get('quiz_answers', '{}'));

// Use in conditional logic
if (w2w.get('is_premium', false)) {
    // Premium user logic
}

// Use in request headers
const token = w2w.get('auth_token', '');

Related Methods

  • w2w.get(key, defaultValue) - Retrieve saved data
  • w2w.set(key, value, callback) - Save data
  • w2w.setUserProperties(properties, callback) - Save multiple properties at once
  • w2w.showToast(message, type, time) - Show user notifications
  • w2w.moveToNextScreen() - Navigate to next screen