Scoping problem with setEmbeddedData() | XM Community
Skip to main content
Question

Scoping problem with setEmbeddedData()

  • March 31, 2022
  • 2 replies
  • 26 views

I am trying to run code similar to the following:
Qualtrics.SurveyEngine.addOnPageSubmit(function() {
jQuery.getJSON([[url]], function(data) {
variable = 1
});
// other_variable = 10

Qualtrics.SurveyEngine.setEmbeddedData('variable', variable)
});
However, nothing gets saved into the embedded data. If I put

setEmbeddedData()
inside the
getJSON()
function, it still does not work. The only way I can embed data is by making a variable similar to
other_variable
which is not inside
getJSON()
.
I have tried to use the
var
keyword and placing the
getJSON()
function in global scope. Please help me fix this. Thanks!

2 replies

Rudi
QPN Level 3 ●●●
Forum|alt.badge.img+16
  • QPN Level 3 ●●●
  • April 1, 2022

Hi shehryar_37
have you tried to define the variable first and then call the function in order to store the return value in the variable?
something like

var variable = jQuery....
Best regards

Rudi


TomG
Level 8 ●●●●●●●●
Forum|alt.badge.img+27
  • Level 8 ●●●●●●●●
  • April 1, 2022

You should use var on your variables to make them local to the function. However, that isn't your primary issue. The primary issue is that getJSON is asynchronous; the JS doesn't wait for it to finish before proceeding to the following commands. Placing getJSON in addOnPageSubmit means that the page will be submitted and the respondent will have moved onto the next page before getJSON returns a result.
So, if what are are doing really needs to happen when the respondent is ready to move to the next page, but before the page is submitted, you'll need to use a fake Next button that executes getJSON and waits for the result before clicking the real Next button.