I have a form submit button that when clicked fires an AJAX callback.

$form['actions']['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Title...'),
  '#ajax' => [
    'callback' => '::getResponse',
    'wrapper' => 'wrapper',

In the AJAX callback, I would like to save what the user entered, plus what the API responded with. I have tried using form state storage and $form_state->set, but in both cases the values are lost.

Form AJAX callback:

  public function getResponse(array &$form, FormStateInterface $form_state) {
    // API call here...

    $form['response']['#value'] = trim($result["answer"]) ?? $this->t('No answer was provided.');
    return $form['response'];

Is there a way to update the UI and the form state?

  • How/where do you want to use this data? Do you want to pass it back to the front end to use in the ajax response or by some other JS? Or do you want to store some data to use when processing the form submission or whatever?
    – Jaypan
    Mar 4, 2023 at 23:11
  • Don't want to save it to the database, just use it in the next form submission. So the next time the form submits, I have the previous user input and API response.
    – Kevin
    Mar 4, 2023 at 23:14

1 Answer 1


Data can be stored in the form submission using $form_state->set('[ARBITRARY KEY]', $value), then retrieved when the form is rebuilt with $value = $form_state->get('[ARBITRARY KEY]'). On the first form build, $value will be null, as the form has not gone through the ajax yet. On further #ajax rebuilds, $value will contain the value you set in the submit handler. Note that you will have to store the value on the form state in the submit handler, NOT the #ajax callback.

  • How can you have an ajax callback on a submit handler, then?
    – Kevin
    Mar 4, 2023 at 23:28
  • Submit handlers are called before the ajax handler(s).
    – Jaypan
    Mar 4, 2023 at 23:29
  • Ah, gotcha. That works now.
    – Kevin
    Mar 4, 2023 at 23:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.