JSON definition · shared/definitions/save-response.jsonView on GitHub
{
"title": "Contact us",
"completeText": "Send message",
"elements": [
{
"type": "text",
"name": "email",
"title": "Your email",
"inputType": "email",
"isRequired": true
},
{
"type": "comment",
"name": "message",
"title": "How can we help?",
"isRequired": true
}
]
}
Client · src/app/examples/save-response/client.tsx · sjs:save-response.clientView on GitHub
const definition = { // Define the form directly in the page - no database needed
title: "Contact us", completeText: "Send message",
elements: [
{ type: "text", name: "email", title: "Your email", inputType: "email", isRequired: true },
{ type: "comment", name: "message", title: "How can we help?", isRequired: true }
]
};
function createSurvey() {
const survey = new Model(definition);
// Save after completion; SurveyJS offers a retry action if saving fails
survey.onComplete.add(async (sender, options) => {
try {
const response = await fetch("/api/responses", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ formId: "contact", data: sender.data })
});
const { id } = response.ok ? await response.json() : {};
if (!Number.isInteger(id) || id < 1) throw new Error("Missing response ID");
sender.setVariable("responseId", id);
options.showSaveSuccess();
} catch { options.showSaveError("We couldn't save your message. Please try again."); }
});
return survey;
}
Server · src/server/routes/save-response.ts · sjs:save-response.serverView on GitHub
// POST /api/responses: Store submitted answers as one JSON document
// readJson() parses the raw body: {} stays {}, " padded " and "" stay as sent
export async function saveResponse(req: Request) {
const { formId, data } = ((await readJson(req)) ?? {}) as Envelope;
if (formId == null || data == null) throw httpError(400, "Expected { formId, data }");
const id = insertResponse(req, formId, data); // JSON.stringify(data), never a copy of it
return Response.json({ id }, { status: 201 });
}