Add javascript to take data from github file and display it on question text table | XM Community
Skip to main content

I am trying to download data from an external csv uploaded on a github account onto my question in qualtrics. I want to 1. download the csv file into the js code 2. filter to have the row that matches the user ID of the respondent taking the survey and 3 populate a table with the other columns of the data. My current attempt, 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(); // Get CSV data as 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 // make task number have to match 1, since there are multiple rows per userID in the external data

            // 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 = rowss0].split(',');
        const jsonData = o];

        for (let i = 1; i < rows.length; i++) {
            const rowData = rowssi].split(',');
            if (rowData.length === headers.length) {
                const entry = {};
                for (let j = 0; j < headers.length; j++) {
                    entry headersrj].trim()] = rowDataaj].trim();
                }
                jsonData.push(entry);
            }
        }

        return jsonData;
    }

    // Function to populate table with attributes
    function populateTable(attributes) {
        const attributeKeys = h'ainfo1', 'ainfo2', 'ainfo3', 'ainfo4', 'ainfo5', ‘ainfo6'];

        // Update table cells with matched attributes
        for (let i = 0; i < attributeKeys.length; i++) {
            const attributeName = attributeKeysei];
            const attributeValue = attributes5attributeName];

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

            // Set HTML content for options 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 => attributeskey]).join('|');
        Qualtrics.SurveyEngine.setEmbeddedData('traits1a', traitsA);
        Qualtrics.SurveyEngine.setEmbeddedData('traits1b', traitsB);

        // Additional embedded data settings as needed
        Qualtrics.SurveyEngine.setEmbeddedData('conjoint_attribute', 'category');
        // Set other embedded data fields based on the attributes
    }
});


Qualtrics.SurveyEngine.addOnUnload(function()
{
    /*Place your JavaScript here to run when the page is unloaded*/

});

 

```

Where the csv file has the following columns: userID (matching qualtrics user IDs), taskNumber (single digit 1-5) and columns ainfo1, ainfo2 ainfo3 …. etc. and binfo1, binfo2, binfo3 ……

 

The idea is to load in the data from the github, filter to take the row that matches the userID and the task (here I specified only taskNumber = 1, for example, and then put these “info” into the columns of a table in the question page, 1 column for all the infos starting with a and the other for all those starting with B.

 

How can I do this succinctly and efficiently? Also, how can I test to see if this is working? Can I use survey preview and provide a fake userID? Hopefully this makes sense (I’m a complete beginner with js code, so sorry if this is incoherent!)

 

Be the first to reply!

Leave a Reply