JSON definition · shared/definitions/save-response.json
View 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 · shared/client/save-response.js · sjs:save-response.client
View on GitHub
// Define the form directly in the page - no database needed
const definition = {
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 }
]
};
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.");
}
});
Server · Endpoints/SaveResponse.cs · sjs:save-response.server
View on GitHub
// POST /api/responses: Store submitted answers as one JSON document
app.MapPost("/api/responses", async (HttpRequest request, SurveyDb db) =>
{
// Read the raw request body: binding to a class would drop unknown keys and re-format numbers such as 1.0
if (await StoredJson.ReadBodyAsync(request) is not JsonObject body
|| body["formId"] is not JsonValue formId || body["data"] is not JsonNode data)
{
return Results.Json(new { error = "Expected { formId, data }" }, statusCode: 400);
}
var id = await StoredJson.InsertResponseAsync(db, formId.ToString(), data); // Preserve float values such as 1.0
return Results.Json(new { id }, statusCode: 201);
});