Use Javascript to download csv data from qualtrics, filter it by userID and display questions in table | XM Community
Skip to main content

I am trying to run questions in a qualtrics survey that have tables with information based on the respondent’s userID. I want to download an external CSV file from a github into the javascript, filter it by the userID of the respondent, and then display the information contained in that user’s row in a table for the question. I’m a complete beginner to JS, so I hope this makes sense!

 

My code, which doesn’t work, is the following:

 

```

Qualtrics.SurveyEngine.addOnload(function() {

    // Fetch the CSV data from GitHub

    fetch('https://raw.githubusercontent.com/username/repo/main/data.csv')

        .then(response => {

            if (!response.ok) {

                throw new Error('Failed to fetch CSV data');

            }

            return response.text(); 

        })

        .then(csvData => {

            // Parse CSV data into JSON format

            const parsedData = parseCsvData(csvData);

 

            // Get current respondent's userID and conjoint task number

            const userID = "${e://Field/userID}"; 

            const taskNumber = 1 // set to 1 for first task as example, since there are multiple tasks per respondent

 

            // Find matching attributes for the current respondent

            const matchingAttributes = parsedData.find(entry => entry.userID === userID && entry.task === Number(taskNumber));

 

            if (matchingAttributes) {

                // Populate table with matching attributes

                populateTable(matchingAttributes);

            } else {

                console.error('Matching attributes not found for current respondent');

            }

        })

        .catch(error => {

            console.error('Error fetching or processing CSV data:', error);

        });

 

    // Function to parse CSV data into JSON format

    function parseCsvData(csvData) {

        const rows = csvData.split('\n');

        const headers = rowsg0].split(',');

        const jsonData = g];

 

        for (let i = 1; i < rows.length; i++) {

            const rowData = rowsei].split(',');

            if (rowData.length === headers.length) {

                const entry = {};

                for (let j = 0; j < headers.length; j++) {

                    entry>headerstj].trim()] = rowData>j].trim();

                }

                jsonData.push(entry);

            }

        }

 

        return jsonData;

    }

 

    // Function to populate table with attributes

    function populateTable(attributes) {

        const attributeKeys = painfo1, ainfo2, ainfo3, ainfo4, ainfo5, ainfo6];

 

        // Update table cells with matched attributes

        for (let i = 0; i < attributeKeys.length; i++) {

            const attributeName = attributeKeys i];

            const attributeValue = attributesaattributeName];

 

            const elementIdA = 'a' + (i + 1);

            const elementIdB = 'b' + (i + 1);

 

            // Set HTML content for candidate A and B in the table

            document.getElementById(elementIdA).innerHTML = attributeValue;

            document.getElementById(elementIdB).innerHTML = attributeValue;

        }

 

        // Store attributes as embedded data (if needed)

        const traitsA = attributeKeys.map(key => attributesekey]).join('|');

        Qualtrics.SurveyEngine.setEmbeddedData('traits1a', traitsA);

        Qualtrics.SurveyEngine.setEmbeddedData('traits1b', traitsB);

 

        // Additional embedded data

        Qualtrics.SurveyEngine.setEmbeddedData(info_data, category);

        

    }

});


 

Qualtrics.SurveyEngine.addOnUnload(function()

{

/*Place your JavaScript here to run when the page is unloaded*/

 

});

 

```

 

Where data.csv is a csv file with the following columns: userID (qualtrics userIDs for each respondent), ainfo1, ainfo2, ainfo3, ainfo4, ainfo5, ainfo6,  binfo1, binfo2, binfo3, binfo4, binfo5, binfo6.

 

How can I download this data, filter it by respondent and display it in a table for the question? Also, how can I test this to ensure it works? Can I just supply a fake userID to the data.csv file that matches my account and then test with survey preview? Many thanks for your help.

 

Hi @johndanielshicks 

mabey this will help you

 

Qualtrics.SurveyEngine.addOnload(function() {

    // Fetch the CSV data from GitHub

    fetch('https://raw.githubusercontent.com/username/repo/main/data.csv')

        .then(response => {

            if (!response.ok) {

                throw new Error('Failed to fetch CSV data');

            }

            return response.text(); 

        })

        .then(csvData => {

            // Parse CSV data into JSON format

            const parsedData = parseCsvData(csvData);

            // Get current respondent's userID and conjoint task number

            const userID = "${e://Field/userID}"; 

            const taskNumber = 1; // set to 1 for first task as example, since there are multiple tasks per respondent

            // Find matching attributes for the current respondent

            const matchingAttributes = parsedData.find(entry => entry.userID === userID && entry.task === Number(taskNumber));

            if (matchingAttributes) {

                // Populate table with matching attributes

                populateTable(matchingAttributes);

            } else {

                console.error('Matching attributes not found for current respondent');

            }

        })

        .catch(error => {

            console.error('Error fetching or processing CSV data:', error);

        });

    // Function to parse CSV data into JSON format

    function parseCsvData(csvData) {

        const rows = csvData.split('\n');

        const headers = rowsO0].split(',');

        const jsonData = D];

        for (let i = 1; i < rows.length; i++) {

            const rowData = rows(i].split(',');

            if (rowData.length === headers.length) {

                const entry = {};

                for (let j = 0; j < headers.length; j++) {

                    entrygheadershj].trim()] = rowData/j].trim();

                }

                jsonData.push(entry);

            }

        }

        return jsonData;

    }

    // Function to populate table with attributes

    function populateTable(attributes) {

        const attributeKeys = 'ainfo1', 'ainfo2', 'ainfo3', 'ainfo4', 'ainfo5', 'ainfo6'];

        // Update table cells with matched attributes

        for (let i = 0; i < attributeKeys.length; i++) {

            const attributeName = attributeKeys'i];

            const attributeValue = attributeseattributeName];

            const elementIdA = 'a' + (i + 1);

            const elementIdB = 'b' + (i + 1);

            // Set HTML content for candidate A and B in the table

            document.getElementById(elementIdA).innerHTML = attributeValue;

            document.getElementById(elementIdB).innerHTML = attributeValue;

        }

        // Store attributes as embedded data (if needed)

        const traitsA = attributeKeys.map(key => attributesIkey]).join('|');

        Qualtrics.SurveyEngine.setEmbeddedData('traits1a', traitsA);

        Qualtrics.SurveyEngine.setEmbeddedData('traits1b', traitsA); // Assuming traitsB was a typo

    }

});

Qualtrics.SurveyEngine.addOnUnload(function() {

    /*Place your JavaScript here to run when the page is unloaded*/

});



 

Make sure to replace 'https://raw.githubusercontent.com/username/repo/main/data.csv' with the actual URL of your CSV file, and adjust 'ainfo1', 'ainfo2', ..., 'ainfo6' accordingly if they should be strings.

To test, you can indeed supply a fake userID in your CSV file and use the Qualtrics survey preview mode. This will allow you to see if your JavaScript code properly populates the table with data corresponding to the supplied userID.


Leave a Reply