How do I submit a form via AJAX? I'm using the Webform module for Drupal 8. The module confirmation settings for a form are the following:


Page (redirects to new page and displays the confirmation message)
Inline (reloads the current page and replaces the webform with the confirmation message.)
Message (reloads the current page/form and displays the confirmation message at the top of the page.)
URL (redirects to a custom path or URL)
URL with message (redirects to a custom path or URL and displays the confirmation message at the top of the page.)


But how am I able to submit a form via AJAX so that the page doesn't reload on submit, but a confirmation message still replaces the form? What did I do wrong?



EDIT:

Here is the solution which works:

First you have to hook the form alter function and set an AJAX callback (as in echo's answer):

use \Drupal\Core\Form\FormStateInterface;

function MYTHEME_form_alter(&amp;$form, FormStateInterface $form_state, $form_id)
{
  if ( isset($form['#webform_id']) &amp;&amp; $form['#webform_id'] == 'MYWEBFORM' )
  {
    // add an AJAX callback to the form submission
    $form['actions']['submit']['#ajax'] = array(
      'callback' =&gt; '\Drupal\MYMODULE\Controller\DefaultController::processFormSubmission',
      'event' =&gt; 'click',
    );
  }
}


Then in the processFormSubmission function you can process the form (put use \Drupal\Core\Form\FormStateInterface; at the top of your file) like:

// Instantiate an AjaxResponse Object to return.
$ajax_response = new \Drupal\Core\Ajax\AjaxResponse();

/* do sth */

// in the DOM: replace the form with the text 'form submitted'
$ajax_response-&gt;addCommand(new \Drupal\Core\Ajax\HtmlCommand('#MYFORM', 'form submitted'));

return $ajax_response;
I can't post all the code you would need, but essentially you will want to do a form alter, and add an #ajax item on the submit button and point it at a callback. This callback will perform validation and submission - at the end of it you can issue a ReplaceCommand. Here's an example:

function mymodule_form_submit($form, FormStateInterface $form_state) {
  // code here to handle the submission aspect
  // you'll need to manually submit form value data to Webform using webform api

  // if successful, this is the response
  $response = new AjaxResponse();
  $response-&gt;addCommand(new ReplaceCommand('selector', 'data'));
  return $response;
}


Where selector is an HTML element, and data is what you want to replace it with.

Sounds like you would want the selector to be the id of the container wrapping the form, and the replacement should be the confirmation message from Webform (you'd have to get it from fetching the config of that form). This will cause a non page refresh and instead, the form will be replaced with the confirmation message.