JSON definition · shared/definitions/choices-from-web.jsonView 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 · src/app/examples/choices-from-web/client.tsx · sjs:choices-from-web.clientView 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 · src/server/routes/choices-from-web.ts · sjs:choices-from-web.serverView on GitHub
// GET /api/offices?region= — {region} from the form arrives as a query parameter
export function listOffices(req: Request) {
const region = query(req, "region") ?? ""; // the first ?region=, or none
return Response.json(db(req).prepare("SELECT id, name FROM offices WHERE region = ? ORDER BY name").all(region));
}
// GET /api/countries — a proxy: the browser can't call a service without CORS, your server can
export async function listCountries() {
let countries = cache.get<Country[]>("countries");
if (!countries) {
try {
const response = await fetchWithTimeout("https://restcountries.com/v3.1/all?fields=name,cca2", { timeout: 5000 });
countries = ((await response.json()) as RestCountry[]).map((country) => ({ code: country.cca2, name: country.name.common }))
.sort((a, b) => a.name.localeCompare(b.name));
cache.set("countries", countries, DAY);
} catch (error) { // down, or a different answer: serve the bundled list for 10 minutes, not a timeout per request
console.warn(`restcountries.com failed (${(error as Error).message}); serving shared/seed/countries.json`);
countries = bundledCountries;
cache.set("countries", countries, 10 * 60 * 1000);
}
}
return Response.json(countries, { headers: { "Cache-Control": "public, max-age=86400" } });
}