Drupal 8 - Form submission without reloading using Ajax

By xngo on March 8, 2019


It is assumed that you know how to create a form. If not, see Create a form in Drupal 8.

Form submission requires a page reload. What we want is to submit a form without refreshing the page. Drupal provides a way to do this using Ajax.

The process is still the same as creating a form but in your form class, simply use Ajax calls.

Create a routing for the form

Add the routing information in ./modules/tradesteps/tradesteps.routing.yml, like the following:

  path: '/my_form_ajax'
    _form: 'Drupal\tradesteps\Form\MyFormAjax'
    _title: 'My Form Ajax'
    _permission: 'access content'

Implement your form class

Now, you have to implement MyFormAjax class. Add the following code in ./modules/tradesteps/src/Form/MyFormAjax.php.

namespace Drupal\tradesteps\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
// Use for Ajax.
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
class MyFormAjax extends FormBase {
    * Build the simple form.
    public function buildForm(array $form, FormStateInterface $form_state) {
        // Add input field called title.
        $form['title'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Title'),
            '#description' => $this->t('Title must be at least 15 characters in length.'),
            '#required' => TRUE,
        // Attach Ajax callback to the Submit button.
        $form['actions']['submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Submit'),
            '#ajax' => [
                'callback' => '::setMessage',
        // Placeholder to put the result of Ajax call, setMessage().
        $form['message'] = [
            '#type' => 'markup',
            '#markup' => '<div class="result_message"></div>',
        return $form;
    public function setMessage(array $form, FormStateInterface $form_state) {
        $response = new AjaxResponse();
            new HtmlCommand(
                '<div class="my_message">Submitted title is ' . $form_state->getValue('title') . '</div>')
        return $response;
    * Implements a form submit handler.
    public function submitForm(array &$form, FormStateInterface $form_state) {
        // Nothing to do. Use Ajax.
    public function getFormId() {
        return 'tradesteps_simple_form_ajax';

Test the input form

  1. Clear your cache.
  2. Open http://your-domain.com/my_form_ajax
  3. Type in your title and then click on the Submit button.

Drupal form submission using Ajax


  • https://github.com/xuanngo2001/drupal-form-ajax

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.