Skip to content

Instantly share code, notes, and snippets.

@richarddmorey
Last active December 28, 2023 16:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save richarddmorey/7a097f08dc1db7203875d9a35ad508f4 to your computer and use it in GitHub Desktop.
Save richarddmorey/7a097f08dc1db7203875d9a35ad508f4 to your computer and use it in GitHub Desktop.
Testing SurveyJS and Rmarkdown
---
title: "Test SurveyJS and Rmarkdown"
output:
html_document:
css: "https://unpkg.com/survey-jquery/survey.min.css"
editor_options:
chunk_output_type: console
---
A test javascript survey by building a JSON object for [SurveyJS](https://surveyjs.io/).
See the basic [SurveyJS tutorial](https://surveyjs.io/Documentation/Library?id=Getting-Started-The-Very-Basics).
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(jsonlite) # jsonlite needed to create JSON survey object
# Convenience function for creating a question
new_question = function(title, type = 'text'){
list(title = unbox(title), type = unbox(type))
}
```
```{r}
# Get the SurveyJS code from unpkg
htmltools::tags$script(src = 'https://unpkg.com/survey-jquery')
```
```{r}
# Create survey
P1 = list(
elements = list(
new_question(title = "What is your name?"),
new_question(title = "What is your favorite color?")
)
)
pages = list(pages = list(P1))
# Full survey object
json_survey = toJSON(pages, auto_unbox = FALSE, pretty = TRUE)
# Inject JSON survey object into HTML as script
htmltools::tags$script(glue::glue('\n\nvar surveyJSON =\n{json_survey}\n\n'))
```
The survey will be placed below.
::: {#surveyContainer}
:::
```{js}
// What to do when the "Complete" button is clicked
function sendDataToServer(sender) {
var resultAsString = JSON.stringify(sender.data);
alert(resultAsString); //Send an AJAX request to your web server here...
}
// Boiler plate code to generate the survey from the JSON
var survey = new Survey.Model(surveyJSON);
survey.onComplete.add(sendDataToServer);
$("#surveyContainer").Survey({model:survey});
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment