SurveyJS PHP Backend Integration with Laravel /

Translate with AI

Translate with AI

Use when: Authors need to translate forms into multiple languages quickly.

Read this step in the docs

Try this

  1. The Translations tab opens with Deutsch, Français and Español added, and Español selected. Press Auto-translate All (the language list is in the side panel, Languages), or tick another language to translate into it too.
  2. Open Requests and expand POST /api/translate: it carries the strings and the locales, and it is the only outbound request.
  3. Without AI_API_KEY, the endpoint answers 501, and Requests shows its message.

Commercial client licence: without SURVEYJS_LICENSE_KEY the component shows a licence banner.

    No requests yet.

      What the server stored

      Source on GitHub Definition: shared/definitions/creator-load-save.json Commercial client licence: without SURVEYJS_LICENSE_KEY the component shows a licence banner

      Client · shared/client/ai-translation.js · sjs:ai-translation.client View on GitHub
      // Creator asks for machine translation; your server calls the AI provider
      creator.onMachineTranslate.add(async (_, options) => {
        const res = await fetch("/api/translate", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ strings: options.strings, from: options.fromLocale, to: options.toLocale })
        });
        options.callback(res.ok ? await res.json() : []);   // same order as options.strings; [] when it failed
      });
      Server · routes/examples/ai-translation.php · sjs:ai-translation.server View on GitHub
      // POST /api/translate — strings in, translated strings out (same order); nothing goes to SurveyJS
      Route::post('/api/translate', function (Request $request) {
          abort_unless(config('surveyjs.ai.api_key'), 501, 'Set AI_API_KEY to enable translation');
          ['strings' => $strings, 'from' => $from, 'to' => $to] = $request->only(['strings', 'from', 'to']) + ['strings' => [], 'from' => '', 'to' => ''];
      
          $translated = AiTranslation::translate($strings, $from, $to);            // any OpenAI-compatible provider: your key, your choice
          abort_unless(is_array($translated) && count($translated) === count($strings), 502, 'The AI provider returned an unexpected answer');
      
          return response()->json($translated);                                    // what options.callback() takes
      });