Search code examples
javascriptqualtrics

How to write information from browser console into qualtrics datafile using javascript


I'm trying to extract information from the browser console into my qualtrics datafile. The code below records reaction time to the first keystroke ('console.log(rt)'). These reaction times are recorded in my browser console, but I'm wondering how I can write that data into my qualtrics datafile. Any ideas would be appreciated. Thanks!

Qualtrics.SurveyEngine.addOnload(function()
{
  var pageStart = new Date(); 
  var trialstart = pageStart.getTime();
  this.hideNextButton();
  this.hidePreviousButton();
  var that = this;
  Event.observe(document, 'keydown', function keydownCallback(e) {
    var choiceID = null;
    switch (e.keyCode) {
      case 83: // 'S' was pressed
        choiceID = 1;
        break;
      case 68: // 'D' was pressed
        choiceID = 2;
        break;
    }
    if (choiceID) {
      var day = new Date();
	  var trialend = day.getTime();
	  let rt = trialend - trialstart;
	  console.log(rt);
      Event.stopObserving(document, 'keydown', keydownCallback);
      that.setChoiceValue(choiceID, true);
    }
  });
  });

EDITED SCRIPT

Qualtrics.SurveyEngine.addOnReady(function()
{
  var pageStart = new Date(); 
  var trialstart = pageStart.getTime();
  this.hideNextButton();
  this.hidePreviousButton();
  var that = this;
  Event.observe(document, 'keydown', function keydownCallback(e) {
    var choiceID = null;
    switch (e.keyCode) {
      case 83: // 'S' was pressed
        choiceID = 1;
        break;
      case 68: // 'D' was pressed
        choiceID = 2;
        break;
    }
    if (choiceID) {
      var day = new Date();
	  var trialend = day.getTime();
	  let rt = trialend - trialstart;
	  var trials ="${e://Field/ed_var}";
	   if(trials.length > 0) trials += ",";
	  Qualtrics.SurveyEngine.setEmbeddedData('ed_var', trials + rt); 	
	  Event.stopObserving(document, 'keydown', keydownCallback);
      that.setChoiceValue(choiceID, true);
    }
  });
  });


Solution

  • Use:

    Qualtrics.SurveyEngine.setEmbeddedData('ed_var', rt);
    

    Where ed_var is an embedded variable that has previously been declared in the survey flow.

    Also, you should change addOnload to addOnReady. addOnload often runs before the buttons are present, which can cause an error when you try to hide them.

    Edit: If you create embedded data fields for all the loops in the survey flow, then you could pass their names into the loop as Field 2 and pipe ${lm://Field/2} into your JavaScript:

    var ed_var = "${lm://Field/2}";
    ...
    Qualtrics.SurveyEngine.setEmbeddedData(ed_var, rt);
    

    If you want one variable that contains a comma separated list of trials it would be something like:

    var trials = "${e://Field/ed_var}";
    if(trials.length > 0) trials += ",";
    ...
    Qualtrics.SurveyEngine.setEmbeddedData('ed_var', trials + rt);