SurveyGizmo Scripting Control Syntax

Please Note:This tutorial is out of date. If you're still using v2 it may be helpful, but if you're using Version 3 of the SurveyGizmo software, please disregard this tutorial. We have a new tutorial with updated information here: Custom Scripting Documentation
SurveyGizmo Script allows you to create complex logic and calculations from within your survey. It does require some knowledge of programming. It can be added to your survey by clicking Add Action in the top-right or bottom-right of the survey page and selecting the SurveyGizmo Scripting Control option. Note: Custom Scripts should be at the TOP of the page in 99% of cases! SurveyGizmo Script follows PHP syntax rules with several exceptions:
  • You cannot define classes and any created functions must start with 'sgapi'.
  • The following control structures are available: for, foreach, if, elseif, else, while, and switch.
  • The functions you can call are listed below.
  • All variables begin with %% rather than $ (all other rules are the same).
  • %%output is your output stream. It will display text & html directly to the survey page.
If you have suggestions on new functions please email them to support@sgizmo.com.

Script Functions

These are the bulk of the SurveyGizmo Scripting functions available to the script control.

sgapiSubmitSurvey() This function records the current survey as a 'partial'. It also records a snapshot of the survey information for immediate reporting

sgapiSubmitSurveyComplete() This function submits the survey as a "Complete". All collected data in the survey is also submitted to reporting.

sgapiGetValue(%%questionID) This function gets the value of an answered question (or null, if not answered) and returns it. In most cases, a single value is returned (a string). The following question types will return an array with the keys assigned as [O0], [O1], [O2], etc. and the values as the entered/selected values in the survey:

  • Multiple Text Fields
  • Checkbox (The number in the key represents the Option sku, first option listed in the survey is 0)
  • Image Choice (Multi-Select)
  • Ranking - Table Format (Returns the rank of each column in order)
  • Continuous Sum
  • A single row of a Table of Checkboxes
  • A single row of a Table of Drop-Down Menus
  • A single row of a Table of Textboxes
  • A single row of a Star Ranking Table
Note: The Multiple Drop-Downs questions type is not accessible via sgapiGetValue.

sgapiCheckboxTotalChecked(%%questionID) This function returns the number of checkboxes selected for the given question.

sgapiGetScore(%%questionID) This function is identical to the function sgapiGetValue.

sgapiURLValue(%%name) This function returns the value of a query string variable passed into the survey where '%%name' is the name of the url variable.

sgapiResultsQuestionAverage(%%questionID,%%query = "") The first of the real-time reporting functions. This returns the average answer for the question id given across all completed surveys in real time. %%query allows you to optionally specify a query string variable to filter by. Like this: "urlvar_fname=vanek" will return the average value for this question by people with the first name 'vanek'. Note: You must prepend the variable name in the script (not in the query string) with 'urlvar_'.

sgapiResultsQuestionTotal(%%questionID) The next real-time reporting function. This returns the total answer for the question id given across all completed surveys in real time. For instance, if you ask in a textbox question for the number of guests (an Auto-Format as Whole Number text field question), this function can be used to get a total number of guests entered in so far by all previous respondents.

sgapiGetQuestionResponseCount(%%questionID,%%osku = null) This is also a real-time reporting function. It allows you to query the number of times a question has been answered. It's a count, not an average. By passing an "option sku" you can see how many times a question was answered a particular way. This function is very useful for programming quota limits! Helpful Tip: %%osku should be quoted out "%%osku" to avoid issues with an osku of zero. Show/Hide Example

sgapiGetQueryResponseCount(%%name) This function returns the number of responses (completes) that have been collected for the current survey. It takes an optional "%%name" parameter that filters by a URL variable. %%name should be in the format of: "urlvar_VariableName=Value". Thus, to filter for a variable called 'domain' and a value called 'bob.com', you would use:

%%name = 'urlvar_domain=bob.com';
Show/Hide Example

sgapiSetValue(%%questionID,%%value) This function populates the response of a hidden, text, essay, radio button, or drop-down menu question when %%value is a 'string'. If %%value is an array(), you can populate a checkbox question. This can also be used for a list of drop-downs, radio button table/matrix, and checkbox table/matrix if you specify the %%questionID of the table's row (not the table's question ID) and submit the appropriate format of %%value. You can also use it set script content to write dynamic scripts! NOTE: When setting values on the same page, the custom script must be at the top of the page!

sgapiSetTitle(%%questionID,%%value,%%language = "English") This function sets the title of a question or the text of a description area. HTML is allowed.

sgapiGetTitle(%%questionID,%%language = "English") This function returns the 'title' of a question.

sgapiSetHTMLEmail(%%questionID,%%value,%%language = "English") This function sets the content of an HTML email (auto-responder).

sgapiSetTEXTEmail(%%questionID,%%value,%%language = "English") This function sets the TEXT version of an auto-responder's body content.

sgapiGetQuestionOptionSelected(%%questionID) This function is deprecated and should not be used. Use sgapiGetValue. This function returns a zero-based index of the option selected for a Radio, Multi-Select Menu, Image Select or Drop-Down Menu question. (If the question is randomized, the index is based on the un-randomized version of that question).

sgapiHideQuestion(%%questionID,%%hide) This function hides or shows a question (the %%hide attribute is set to 'true' [without quotes, lowercase] to hide and 'false' [without quotes, lowercase] to show).

sgapiShowPage(%%pageID,%%show) This function shows or hides a page (the %%show attribute is set to 'true' [without quotes, lowercase] to show and 'false' [without quotes, lowercase] to hide), default is to show it ('true') [without quotes, lowercase].

sgapiHidePage(%%pageID,%%show) Pending future upgrade. Place a feature request if you would like to express interest in this function.

sgapiRemoveOption(%%questionID,%%option) This is the scripting way of doing Dynamic Show/Hide. This function removes (hides) a multiple choice option (by reporting value as %%option). For table questions it hides the column associated with that option for all rows. Show/Hide Example

sgapiSetRequired(%%questionID,%%req) This function toggles the "Required" status of a question (the %%req attribute is set to 'true' [no quotes, lowercase] to require and 'false' [no quotes, lowercase] to not require).

sgapiAllQuestionsOfType(%%type,%%pagenumber = 1) This function returns an array of all the questions (of a particular type) on a particular page. Possible values for %%type: "RADIO", "CHECKBOX"...

sgapiTrimStr(%%value) This function trims a string of trailing and the preceding whitespace.

sgapiStrPos(%%haystack,%%needle,%%offset = 0) This function returns the offset of a substring within a string.

sgapiSubStr(%%string,%%offset = 0,%%len = 255) This function returns a substring of a string based on length and position.

sgapiStrLen(%%string) This function returns the length of a string.

sgapiStr_replace(%%search,%%replace,%%subject) This function looks for %%search inside of %%subject and overwrites %%search with %%replace.

sgapiIsArray(%%string) Evaluates as 'true' if the variable is an array.

sgapiCSVSplit(%%string) Splits the given string into an array (comma separated values).

sgapiCount(%%array) Returns the number of elements in an array. Show/Hide Example

sgapiArraySet(%%array,%%index,%%string) Sets the value of an item with an array (supports hash tables).

sgapiArrayGet(%%array,%%index) Gets the value of an item in an array.

sgapiJumpToPage(%%pageID) This function jumps the survey taker to the specified page ID. Hover your mouse over the 'Delete Page' option on the target page and look at the bottom of the browser window for the target URL. The variable qid=## gives you the page id number. Note:Be advised there can be a conflict when using this function to jump to a page that has the same Page ID as the Page Number of the script. Fix: Copy the page that is the target of the jump, delete the original page, and use the new Page ID.

sgapiDisqualify(%%message) This function disqualifies the user and ends the survey, displaying a customized message to the user.

sgapiCreateLoopCount(%%increment) This function creates an array of numbers (1 to 500) that can be used to power a loop.

sgapiStrtotime(%%string,%%time) This function takes a string and converts it to a Unix timestamp, relative to the timestamp %%time. %%time is optional.

sgapiDate(%%format,%%time) This function converts %%time, a Unix timestamp, into a human readable date and time. %%time is optional and defaults to the current time. See the PHP date() function for possible values of %%format.

sgapiGetResponseBySGUID(%%surveyid,%%sguid) This function will return an array of the status, responseid and the edit link for any response associated with that SGUID and survey. Evaluates as false if the SGUID does not exist.

sgapiRandomizeTable(%%questionID) Given the Question ID of a table, this function will shuffle the rows of the table and return the newly ordered rows. (NOTE: The table has already been shuffled after the function call, the return is just useful for seeing the new order of the rows.)

sgapiGetTableQuestionTitles(%%questionID) This function accepts the Question ID of a table and returns an array in the following format: [questionID] => 'title' (i.e. the question id is the key and the title is the value for each item in the array).

sgapiSetTableOrderByTable(%%tableID,%%referenceTableID,%%language='English') This function accepts two table Question IDs and orders the rows of the %%tableID Table by the %%referenceTableID. Useful when carrying down randomized table rows to a copy of the original table.

sgapiImplode(%%glue, %%pieces) Like the PHP implode() function. Given an array of %%pieces it will create a string delimited by the string %%glue.

sgapiExplode(%%delimiter, %%string, %%limit=null) Like the PHP explode() function. Given a string %%string it will create an array breaking the string up by %%delimiter. Limit is optional. If set, the returned array will only contain up to %%limit elements.

sgapiPrint_R(%%mixed) Given any variable it will return a string of that variable's contents. Use with %%output to print to the screen. Very useful when looking at arrays of data or objects. Show/Hide Example

sgapiShuffle(&%%array) Given an array this function will randomly reorder the array. It will evaluate as true on success and false on failure.

sgapiArray_Pop(%%array) Given an array this function will return the last element of the array and remove that element from the array itself. Show/Hide Example

sgapiArray_Diff(%%array1,%%array2) Given two arrays this function will compare %%array2 against %%array1 and return an array of values that are present in %%array1 but not present in %%array2.

sgapiArrayMerge(%%array1,%%array2) Given two arrays this function will append the elements of %%array2 to the end of %%array1 and return combined elements (the array is reindexed).

sgapiArrayUnique(%%array1) Given an array, this function will remove any elements that contain duplicate values and return the deduped array.

sgapiArray_Flip(%%array1) Given an array this function will exchange an element's key with that element's value and return the resulting array.

sgapiCurrentPageTitle() This function will return the title of the page it is currently on. This is useful if you'll be copying the script and moving it to different pages.

sgapiURLEncode(%%str) Given a string this function will URL encode it making your links safe.

sgapiRand(%%min, %%max) Generates a random number (typically 9 or 10 digits long). If the optional %%min and %%max integers are specified, it will generate a number between %%min and %%max instead.

sgapiRound(%%number,%%decimal=0) Returns the %%number rounded to the nearest whole number by default. If the optional %%decimal is also included, it defines the number of decimal positions to include.

Show/Hide Example

sgapiSqrt(%%number) Returns the square root of the value in %%number.

sgapiLog(%%number,%%base=10) Returns the natural logarith of %%number. If %%base is provided (optional), it is used in the following mathematical fashion: Log%%base%%number

sgapiPow(%%base,%%power) Returns the value of %%base raised to the power of %%power. Mathematically written as: %%base%%power

sgapiIs_Null(%%variable) Returns either TRUE or FALSE if the variable passed is Null. This is equivalent to the is_null function in PHP. Note: it is a capital i and capital n in the function name.

sgapiMd5(%%string) Returns the MD5 hash of the provided string. Can be used to compare two strings for an exact match by comparing their MD5 hash values.

sgapiStrCaseCmp(%%str1,%%str2,%%case=false) This function will compare %%str1 with %%str2 in a case-insensitive manner (default), returning the results as either a negative number (str1 < str2), 0 (match), or a positive number (str1 > str2) in the same manner as the PHP StrCaseCmp function. If the optional %%case is passed as 'true' (no quotes, lowercase), the comparison will be case-sensitive like the PHP StrCmp function.

The %%output Variable

%%output literally is echo'd to the page, where the custom script is present. If there is a problem with the script, it will not output properly. Imagine, in PHP terms, that whatever is captured in the %%output variable would be subject to this automatically at the end of the script:
echo %%output;
That is what happens automatically. It does NOT need to be added (and would create an error) to your script. Thus, assign values or concatenated values works fine. Example:
%%output = "This is a test. This is a " . sgapiGetValue(%%variable);
%%output .= "
";
%%output .= sgapiPrint_R(%%array);

Example Script

This script example adds up all the checkboxes that are checked on the first and second pages of a survey. If they choose 10 items then it submits the survey. If they choose over 10 it disqualifies them (throws them out of the survey). Less than ten and they are free to proceed to the current (next) page.
%%pagestocheck[] = 1;
%%pagestocheck[] = 2;
%%total = 0;

foreach(%%pagestocheck as %%page)
{
%%questionIDs = sgapiAllQuestionsOfType("CHECKBOX",%%page);
foreach(%%questionIDs as %%questionID)
{
%%total += sgapiCheckboxTotalChecked(%%questionID);
}
}

if(%%total == 10){
sgapiSubmitSurvey();
}

if(%%total > 10){
%%over = %%total - 10;
%%msg = "

You have selected %%total nominees.

"; %%msg .= "I'm sorry but that's ".%%over." too many.

Thanks for your time. "; sgapiDisqualify(%%msg); } else { %%output = "Thus far you have selected ".%%total." nominees"; }

Example Script #2

This script will check two fields for matching data. If the data does not match, it jumps back to that page.
/*=========Variables=========*/
%%field1 = 3; //Question ID of first textbox
%%field2 = 4; //Question ID of second textbox
%%pageid = 1; //Page ID of page containing field1 and field2

/*=========Script=========*/
%%vala = sgapiGetValue(%%field1);
%%valb = sgapiGetValue(%%field2);

if (%%vala != %%valb) sgapiJumpToPage(%%pageid);

Example Script #3

This script prechecks the values of a checkbox question (general categories, Q2) based upon selections in a previous checkbox question (Q1). Q1 has a Question ID of 7 and has the options of:
  • UK
  • China
  • HK
Q2 is on a later page, has a Question ID of 11, and has the options of:
  • Eastern
  • Western
/*=========Variables=========*/
%%questionid1 = 5;
%%questionid2 = 11;

/*=========Script=========*/
%%answerarray = array();
foreach (sgapiGetValue(%%questionid1) as %%value){
  switch(%%value){
    case 'UK':
      %%answerarray[1] = 'Western';
      break;
    case 'China':
    case 'HK':
      %%answerarray[2] = 'Eastern';
      break;
  }
}
sgapiSetValue(%%questionid2,%%answerarray);

Equals Sign ( =, ==, ===, !=, and !== )

The following content is adapted from an article on the equals sign in PHP. There are 3 primary uses of the equals sign within Custom Scripting:
  • Assignment ( = ): Assigns the value on the right to the %%variable on the left
  • Equality ( == ): Checks if the left and right values are equal (used in IF statements!)
  • Identical ( === ): Checks if the left and right values are equal AND the identical type ('1' is a string, 1 is an integer; not identical)
Secondarily, there is also the use of the exclamation point to state not:
  • Not Equal ( != ): Checks if the left and right values are not equal
  • Not Identical ( !== ): Checks if the left and right values are not equal and not identical
%%a = 1; // Sets the value of $a as 1 by assignment
%%b = TRUE; // Sets the value of $b to the boolean TRUE
if (%%a == %%b){
%%output = 'a is equal to b.';
}
if (%%a === %%b){
%%output = 'a is identical and equal to b.';
}
Output: a is equal to b.
%%a = 1; // Sets the value of $a as 1 by assignment
if (%%a != 2){ // if %%a is not equal to 2 then this is a TRUE statement and the IF will be executed
%%output = 'a does not equal 2.';
}
Output: a does not equal 2. As a rule of thumb, IF statements will not use a single equals sign within the evaluated section. Double-check your scripts to ensure your IF statements are double equals signs rather than a single equals sign inside of the parenthesis of an IF statement!

Control Structures

The following explanations are adapted from a PHP reference book, with permission.

if, elseIf, else

if (expr) {
    // If expr is TRUE,  do this, then exit the IF loop
  }elseif (expr2) {
    // If expr is FALSE, and expr2 is TRUE, do this, then exit the loop
  }else{
    // If all expr's are FALSE, do this, then exit
}
There can be only one instance of else in an if statement, but multiple elseif expressions are allowed prior to the else statement. Example:
%%x = 1;
if (%%x < 1){
    %%output = '%%x is less than 1';
  }elseif (%%x == 1){ // Note the double equals, for comparison
    %%output = '%%x is equal to 1';
  }else{
    %%output =  '%%x is neither equal to 1 or less than 1';
}
Output: %%x is equal to 1

Switch

switch (expr) {
  case value:
    // Do this if value matches
    break;
  case value2:
    // Do this if value2 matches
    break;
  default: 	// [optional]
    // Do this if no other cases match. Does not have to be at the end
    break;
}
expr – A string, integer, or float to be compared against A switch evaluates the expr against any number of cases or options, specifying the behavior for each case. Cases can be 'stacked' to allow the same portion of code to be evaluated for different cases:
switch (expr) {
  case value:
  case value2:
    // Do this if value or value2 matches
}
The switch is evaluated line-by-line, and therefore if there was no break command, the case declaration would effectively be ignored and the code would continue to be processed until the switch ends or a break; is reached.
%%x = 1;
switch (%%x) {
  case 1:
    %%output .= '1'; // Note the lack of a break;
  case 2:
    %%output .= '2'; // Without the break, this is processed line-by-line
}
Output: 12 Finally, the default statement is optional, but defines what to do if no cases are matched. It can be used in troubleshooting to identify when you failed to include a case for an expected output. Examples:
%%x = 2;
switch (%%x) {
  case 1:
    %%output .= '1';
    break;
  case 2:
    %%output .= '2';
    break;
  case 3:
    %%output .= '3';
    break;
}
Output: 2
%%x = 'howdy';
switch (%%x) {
  case 'hi':
    %%output .= 'Hi there';
    break;
  default: // Can be anywhere, all cases evaluated before it is used
    %%output .= 'Greetings';
    break;
  case 'hello':
    %%output .= 'Hello there';
    break;
}
Output: Greetings

while

while (expr) {
    // If expr is TRUE,  do this, then evaluate expr again
}
The while loop checks the expr and if it evaluates as true, the script runs through the entire contents of the while until it finishes, then it evaluates the expr again and repeats until the expr evaluates as false. Example:
%%x = 1;
while (%%x <= 3){
    %%output .= "%%x, ";
    %%x++; // increments %%x by adding 1. Short-hand version
}
Output: 1, 2, 3,

do-while

do {
  // Do this
} while (expr);
The do-while loop performs whatever is inside the do statement, checks the expr, then if it evaluates as TRUE, runs through the entire contents of the do until it finishes, evaluating the expr again, and repeating until the expr evaluates as FALSE. Example:
%%x = 1;
do {
    %%output .= "%%x, ";
    %%x++; // Makes %%x = 2, therefore the while will evaluate as false
  } while (%%x <= 1);
Output: 1,

for

for (expr1; expr2; expr3) {
    // If expr2 is TRUE, do this
}
When started, the for loop executes expr1 once at the beginning. Next, expr2 is evaluated. If expr2 is true, the code inside the for loop is executed. When the for loop reaches the end, expr3 is executed before looping and checking expr2 again. Example:
for (%%x = 1; %%x <= 5; %%x++){
    %%output .= %%x;
}
Output: 12345

foreach

foreach (%%array as %%value){
    // Do something
}
// Another form, for keys and values
foreach (%%array as %%key => %%value){
    // Do something
}
The foreach loop goes through all items in an array, assigning a temporary variable name for value and, if chosen, the key as well so they can be used within the executed code inside the loop. Examples:
%%array = array('John' => 20, 'Jane' => 24, 'Joseph' => 28);
foreach (%%array as %%value){
    %%output .= "$value, ";
}
Output: 20, 24, 28,
foreach (%%array as %%name => %%age){
    %%output .= %%name." - ".%%age;
    %%output .= '
'; // XHTML for a line break
}
Output: John - 20 Jane - 24 Joseph - 28

The following two items are used within control structures and perform specific tasks.

break [%%integer]

%%integer – [optional] Specifies the number of nested loops to break out of Exits and stops execution of the current (default) for, foreach, while, do-while, or switch loop. Example:
%%counter = 0;
while (1 == 1){ // Will run forever
    while (0 == 0){ // Will also run forever
        $counter++; // Increment $counter plus 1
        %%output .= $counter;
        if (%%counter == 5){
          break 2;
        }
    }
    %%output .= 'First while loop'; // Never displayed because of break 2;
    break; // Never run, but if it did, would end the first while loop
}
Output: 12345

continue [%%integer]

%%integer – [optional] Specifies the number of nested loops to skip out of Note: The %%integer does not supply the number of iterations to skip, it always only stops the current iteration from continuing any further. Skips the rest of the current loop iteration and if applicable, continues to the next iteration of the loop1. Example:
for (%%x=1;%%x<=10;%%x++){
    if (%%x == 5){
      continue;
    }	// The output never occurs if %%x == 5
    %%output .= %%x;
}
Output: 1234678910

AND, OR, and XOR

SurveyGizmo's scripting language supports the combination or comparison of values within a control structure using special syntax for AND, OR, and XOR:
  • AND is represented as &&
  • OR is represented as ||
  • XOR is represented as xor
if (%%a < 5 && %%a != 0 ){
// if %%a is less than 5 AND %%a is not equal to 0
// then this is a TRUE statement and the IF will be executed
%%output = 'a is 1,2,3, or 4.';
}
if (%%a < 5 || %%a > 10 ){
// if %%a is less than 5 OR %%a is greater than 10
// then this is a TRUE statement and the IF will be executed
%%output = 'a is less than 5 or greater than 10';
}