I.1
Save the response
You need this: Always. This is the whole minimum integration.
The definition can live in the page as a constant: no database, no extra request. When the respondent completes the form, post the answers to one endpoint and store them exactly as they arrive: a response is a single JSON document.
Try this
Posted
Nothing posted yet.
Code that just ran
These regions are read from the files that served this page, the same lines the Server Integration page shows.
shared/client/save-response.js · sjs:I.1.client
View on GitHub
import { Model } from "survey-core";
// The definition can be a constant in the page — no database needed
const definition = {
elements: [
{ type: "text", name: "email", title: "Your email", inputType: "email", isRequired: true },
{ type: "comment", name: "message", title: "How can we help?" }
]
};
const survey = new Model(definition);
// One endpoint: post the answers when the respondent completes the form
survey.onComplete.add(async (sender) => {
await fetch("/api/responses", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ formId: "contact", data: sender.data })
});
});
routes/examples/save-response.php · sjs:I.1.server
View on GitHub
// POST /api/responses — store the answers exactly as they arrive
Route::post('/api/responses', function (Request $request) {
// The raw body, not $request->input(): PHP arrays would turn {} into [] in the stored JSON
$body = json_decode($request->getContent(), flags: JSON_THROW_ON_ERROR);
abort_unless(isset($body->formId, $body->data), 400, 'Expected { formId, data }');
$id = DB::table('responses')->insertGetId([
'form_id' => $body->formId,
'data' => json_encode($body->data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION | JSON_THROW_ON_ERROR), // one JSON document
'created_at' => now('UTC')->toIso8601ZuluString(),
]);
return response()->json(['id' => $id], 201);
});
Definition: shared/definitions/save-response.json