Search code examples
javascriptcookiessession-cookiesqualtrics

Write and Read value from Cookie In Qualtrics


In Qualtrics we're gathering a User ID from the URL (psid) and storing it as embedded data.

We need to send users to a website to view and then complete a survey in HotJar which will redirect them back to Qualtrics to register the user as a complete.

As the website/HotJar can't handle the user id bit I was hoping to write the ID into a cookie in the survey, then, when they're done there and redirected back to Qualtrics we could read the cookie back in and know their ID and that they've finished the section.

I've looked at how to do javascript cookies but don't seem to have anything added onto my computer when doing it so I'm getting something wrong:

Qualtrics.SurveyEngine.addOnload(function()
{
    function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}
    createCookie('blqualtrics',"${e://Field/psid}",7)
});

So any help on how to do this right (and then the other end of reading the cookie and putting the value back into embedded data) would be a great help.


Solution

  • Ah, well, that was easier than I thought:

    Qualtrics.SurveyEngine.addOnload(function()
    {
        /*Place your JavaScript here to run when the page loads*/
    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }
        var x = readCookie('blqualtrics')
    if (x) {
        Qualtrics.SurveyEngine.setEmbeddedData( 'psid', x );
    }
    });
    

    So, there you go, reads the "blqualtrics" cookie in and writes it to "psid" in embedded data (already have an empty psid field in embedded data), brilliant.