SurveyJS PHP Backend Integration with Laravel /

Save Responses

Save Responses

Use when: Your form needs to collect and store submitted answers.

Read this step in the docs

Try this

  1. Fill out the form: Requests stays empty while you type. The JSON schema is a constant in shared/client/save-response.js.
  2. Press Complete. Exactly one POST /api/responses appears: open Requests and expand it to see the posted body and the 201 answer, {"id": …}.
  3. The check at the top of Requests says the stored data is identical to the posted data, and Data shows responses with it. Try spaces around words, an empty message or non-ASCII text such as naïve — 東京.
  4. Press Start over and send another one.

    No requests yet.

      What the server stored

      Source on GitHub Definition: shared/definitions/save-response.json

      Client · shared/client/save-response.js · sjs:save-response.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 })
        });
      });
      Server · routes/examples/save-response.php · sjs:save-response.server View on GitHub
      // POST /api/responses — store the answers exactly as they arrive
      // bootstrap/app.php turns off TrimStrings and ConvertEmptyStringsToNull for /api/*: they would change "  a " and ""
      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 = StoredJson::insertResponse($body->formId, $body->data);   // one JSON document, stored as it arrived: 1.0 stays 1.0
      
          return response()->json(['id' => $id], 201);
      });