JSON definition · shared/definitions/choices-from-web.json
View on GitHub
{
"title": "Choose an office",
"elements": [
{
"type": "panel",
"name": "find_office",
"elements": [
{
"type": "radiogroup",
"name": "region",
"title": "Region",
"colCount": 3,
"defaultValue": "europe",
"isRequired": true,
"choices": [
{
"value": "europe",
"text": "Europe"
},
{
"value": "americas",
"text": "Americas"
},
{
"value": "asia-pacific",
"text": "Asia-Pacific"
}
]
},
{
"type": "dropdown",
"name": "office",
"title": "Office",
"isRequired": true,
"choicesByUrl": {
"url": "/api/offices?region={region}",
"valueName": "id",
"titleName": "name"
}
}
]
},
{
"type": "dropdown",
"name": "country",
"title": "Your country",
"isRequired": true,
"choicesByUrl": {
"url": "/api/countries",
"valueName": "code",
"titleName": "name"
}
}
]
}
Client · shared/client/choices-from-web.js · sjs:choices-from-web.client
View on GitHub
// Use choicesByUrl in the form definition to load lists from API endpoints
// "choicesByUrl": { "url": "/api/offices?region={region}", "valueName": "id", "titleName": "name" }
// "choicesByUrl": { "url": "/api/countries", "valueName": "code", "titleName": "name" }
// SurveyJS replaces {region} with the selected region and reloads the office list when the region changes
// Optional: add your auth header to every choices request
import { settings } from "survey-core";
settings.web.onBeforeRequestChoices = (_, options) => {
options.request?.setRequestHeader("Authorization", `Bearer ${token}`);
};
Server · app/routes/choices_from_web.py · sjs:choices-from-web.server
View on GitHub
# GET /api/offices?region= — {region} from the form arrives as a query parameter
@router.get("/api/offices")
def offices(db: Db, region: str = "") -> list[dict[str, str]]:
return [dict(row) for row in db.execute("SELECT id, name FROM offices WHERE region = ? ORDER BY name", (region,))]
# GET /api/countries — a proxy: the browser can't call a service without CORS, your server can
@router.get("/api/countries")
async def countries(http: HttpClient, cache: Cache) -> JSONResponse:
countries = cache.get("countries")
if countries is None:
try:
answer = await http.get("https://restcountries.com/v3.1/all", params={"fields": "name,cca2"}, timeout=5)
countries = sorted(({"code": c["cca2"], "name": c["name"]["common"]} for c in answer.raise_for_status().json()),
key=lambda country: country["name"])
cache.set("countries", countries, DAY)
except Exception as error: # down, or a different answer: the bundled list for 10 minutes, not a timeout each
log.warning("restcountries.com failed (%s); serving shared/seed/countries.json", error)
countries = json.loads(BUNDLED_COUNTRIES.read_text(encoding="utf-8"))
cache.set("countries", countries, 10 * 60)
return JSONResponse(countries, headers={"Cache-Control": "public, max-age=86400"})