What's wrong with my JavaScript and embedded (external) data? | XM Community
Skip to main content

My Javascript seems to work, but doesn’t return any value other than 0. Here’s the details:

In my survey I want to show respondents the future cost of their child’s college based on an official estimate. To do that, I ask two questions:
1) What college type you hope your eldest child will attend - here they can select 1 of 3 options
2) In how many years will your child start college - this is a text entry that only allows numeric values

I created an embedded data at the very top of the survey flow, called “CollegeCost” and set value to 0. 

I have a csv file saved on an external drive with no access restrictions. In question 2 above I added the following JavaScript. I made sure the names of the csv columns are correct as well as the case-sensitive wording of the answer options. 

In the next survey page I then include the following piped text: ${e://Field/CollegeCost}. This value is always 0 no matter the values I put in the two questions. 

What am I doing wrong?

___________________________

Qualtrics.SurveyEngine.addOnload(function() {
    // Fetch the data from the CSV file
    var csvUrl = "Here I copy-paste the URL with the csv table"; // Replace with your actual CSV URL

    // Map the survey question choices to the CSV column names
    var collegeTypeMap = {
        "2-year Community College, or vocational or apprenticeship": "com_coll",
        "4-year Public University, in-state or out-of-state": "public_four",
        "4-year Private University": "private_four"
    };

    var selectedChoice = "${q://QID8/ChoiceGroup/SelectedChoices}"; // Adjust as necessary
    var collegeType = collegeTypeMapbselectedChoice];

    // Get the text entry for years until college and parse it to an integer
    var yearsUntilCollegeText = "${q://QID10/ChoiceTextEntryValue}"; // Adjust as necessary
    var yearsUntilCollege = parseInt(yearsUntilCollegeText, 10);

    if (isNaN(yearsUntilCollege)) {
        console.error("Invalid number of years entered: " + yearsUntilCollegeText);
        return;
    }

    var targetYear = new Date().getFullYear() + yearsUntilCollege;

    console.log("Fetching data for year: " + targetYear + ", college type: " + collegeType);

    fetch(csvUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.text();
        })
        .then(data => {
            var rows = data.split("\n").map(row => row.split(","));
            var headers = rows0];
            var yearIndex = headers.indexOf("year");
            var typeIndex = headers.indexOf(collegeType);

            console.log("Headers: " + headers);
            console.log("Year Index: " + yearIndex);
            console.log("Type Index: " + typeIndex);

            if (typeIndex === -1) {
                console.error("College type not found in headers");
                return;
            }

            var cost = 0;
            for (var i = 1; i < rows.length; i++) {
                if (parseInt(rowsi]yearIndex], 10) === targetYear) {
                    cost = rowsoi] typeIndex];
                    break;
                }
            }

            console.log("Calculated cost: " + cost);

            // Set the embedded data
            Qualtrics.SurveyEngine.setEmbeddedData('CollegeCost', cost);

            // Update the piped text
            document.getElementById('cost-display').innerText = cost;
        })
        .catch(error => {
            console.error('Error fetching or processing data: ', error);
        });
});

 

You can’t pipe ${e://Field/CollegeCost} until the third page:

  1. Questions
  2. Your JS that sets CollegeCost
  3. Pipe CollegeCost

However, your JS is already set up to display the cost on the second page (the same page with the JS). You just need to add an element with the id ‘cost-display’ to your question text:

<span id='cost-display'></span>

 


Leave a Reply