HTML to generate unique survey links for users

Hello Everyone :wave:

This HTML code snippet provides a straightforward solution for generating unique survey links for each user:

Feel free to use the following code or click here

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate Survey Link</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f0f0f0;
        }

        h1 {
            text-align: center;
        }

        .container {
            max-width: 600px;
            margin: 0 auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        label {
            display: block;
            font-weight: bold;
            margin-bottom: 5px;
        }

        input[type="text"] {
            width: 100%;
            padding: 8px;
            margin-bottom: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            background-color: #007bff;
            color: #fff;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            border-radius: 4px;
        }

        button:hover {
            background-color: #0056b3;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #007bff;
            color: #fff;
        }

        tr:nth-child(even) {
            background-color: #f2f2f2;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Generate Unique Survey Link for Users</h1>

        <label for="emailInput">Email Addresses:</label>
        <input type="text" id="emailInput" placeholder="Enter email addresses separated by commas">

        <label for="surveyIdInput">Survey ID:</label>
        <input type="text" id="surveyIdInput" placeholder="Enter survey ID">

        <label for="channelIdInput">Channel ID:</label>
        <input type="text" id="channelIdInput" placeholder="Enter channel ID">

        <label for="tokenInput">Bearer Token:</label>
        <input type="text" id="tokenInput" placeholder="Enter bearer token ">

        <button onclick="generateLink()" id="generateButton">Generate Survey Links</button>
        <button onclick="stopGeneration()" id="stopButton" style="display: none;">Stop Generate</button>
        <button onclick="downloadCSV()" id="downloadButton" style="display: none;">Download CSV</button>
        <button onclick="clearAll()" id="clearButton" style="display: none;">Clear All</button>

        <table id="outputTable">
            <thead>
                <tr>
                    <th>Email</th>
                    <th>Generated Survey Link</th>
                </tr>
            </thead>
            <tbody>
                <!-- Table rows will be added dynamically by JavaScript -->
            </tbody>
        </table>
    </div>

    <script>
        let surveyId; // Define surveyId as a global variable
        let channelId; // Define channelId as a global variable
        let isGenerating = false; // Flag to track generation status
        let generatedLinks = []; // Array to store generated links

        async function generateLink() {
            if (isGenerating) {
                return; // If generation is already in progress, do nothing
            }

            isGenerating = true;
            document.getElementById('generateButton').style.display = 'none';
            document.getElementById('stopButton').style.display = 'block';
            document.getElementById('downloadButton').style.display = 'none';
            generatedLinks = [];

            const emailInput = document.getElementById('emailInput');
            const emailAddresses = emailInput.value.split(',').map(email => email.trim()); // Split input into an array

            surveyId = document.getElementById('surveyIdInput').value;
            channelId = document.getElementById('channelIdInput').value;
            const authorizationToken = document.getElementById('tokenInput').value;

            const headers = { "Authorization": `Bearer ${authorizationToken}`, "Content-Type": "application/json" };
            const getContactUrl = (email) => `https://api.surveysparrow.com/v3/contacts?search=${email}`;
            const contactOption = { headers };
            const uniqueLinkUrl = "https://api.surveysparrow.com/v3/channels/create_unique_links";

            const outputTable = document.getElementById('outputTable');

            for (const email of emailAddresses) {
                if (!isGenerating) {
                    break; // Stop generation if the "Stop Generate" button is clicked
                }

                const newRow = outputTable.insertRow(-1);

                try {
                    const contactResponse = await fetch(getContactUrl(email), contactOption);
                    const contactData = await contactResponse.json();
                    const contactId = contactData.data[0].id;

                    const uniqueLinkResponse = await fetch(uniqueLinkUrl, uniqueLinkOptions({ contact_ids: [contactId] }, headers));
                    const uniqueLinkData = await uniqueLinkResponse.json();
                    const uniqueLink = uniqueLinkData.data[0].survey_link;

                    generatedLinks.push({ email, link: uniqueLink });

                    const emailCell = newRow.insertCell(0);
                    const linkCell = newRow.insertCell(1);

                    emailCell.innerHTML = email;
                    linkCell.innerHTML = `<a href="${uniqueLink}" target="_blank">${uniqueLink}</a>`;
                } catch (e) {
                    const errorRow = outputTable.insertRow(-1);
                    const errorCell = errorRow.insertCell(0);
                    errorCell.colSpan = 2;
                    errorCell.innerHTML = `Error: ${e.message}`;
                }
            }

            isGenerating = false;
            document.getElementById('generateButton').style.display = 'block';
            document.getElementById('stopButton').style.display = 'none';

            if (generatedLinks.length > 0) {
                document.getElementById('downloadButton').style.display = 'block';
            }
        }

        function stopGeneration() {
            isGenerating = false;
            document.getElementById('generateButton').style.display = 'block';
            document.getElementById('stopButton').style.display = 'none';
        }

        function uniqueLinkOptions({ contact_ids }, headers) {
            return {
                method: "POST",
                headers,
                body: JSON.stringify({
                    survey_id: surveyId,
                    channel_id: channelId,
                    contact_ids
                })
            };
        }

        function downloadCSV() {
            const csvContent = "Email,Generated Survey Link\n" +
                generatedLinks.map(link => `${link.email},${link.link}`).join("\n");

            const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
            const link = document.createElement("a");

            if (navigator.msSaveBlob) {
                navigator.msSaveBlob(blob, "generated_links.csv");
            } else {
                link.href = window.URL.createObjectURL(blob);
                link.download = "generated_links.csv";
                link.style.display = "none";
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }

        function clearAll() {
            // Clear form fields
            document.getElementById('emailInput').value = '';
            document.getElementById('surveyIdInput').value = '';
            document.getElementById('channelIdInput').value = '';
            document.getElementById('tokenInput').value = '';

            // Clear generated links and table
            generatedLinks = [];
            const outputTable = document.getElementById('outputTable');
            outputTable.getElementsByTagName('tbody')[0].innerHTML = '';

            // Hide "Download CSV" and "Clear All" buttons
            document.getElementById('downloadButton').style.display = 'none';
            document.getElementById('clearButton').style.display = 'none';
        }
    </script>
</body>
</html>