Online Survey Tutorials
SurveyGizmo Tutorials and Help Documentation
Table of Contents
Tutorial: SurveyGizmo Scripting Control Syntax
SurveyGizmo Script allows you to create complex logic and calculations from within your survey. It does require some knowledge of programming.
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 the case of multi-answer questions (like a checkbox) it returns an array of answers numerically indexed.
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.
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 take an optional “%%name” parameter that filters by a URL variable.
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!
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 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.
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 of the row titles for that table.
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. Randomization is by Mersenne twister.
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 .= "<br />"; %%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; 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 = "<h1>You have selected %%total nominees.<h1>"; %%msg .= "I'm sorry but that's<font color=red > %%over too many. </font></h1><br><br>Thanks for your time.</h1>"; 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);
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 .= '<br />'; // 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

