Implementing AJAX in controllers or formsfor Drupal 8 , 9 , 10 , and 11

Last updated :  

Introduction

As you continue to develop more interactive and dynamic web applications in Drupal, incorporating AJAX functionality becomes important to improving user experience. AJAX allows for asynchronous web page updates without reloading the entire page, making interactions more seamless and efficient. In this lesson, we'll explore how to implement AJAX within Drupal controllers and forms.

Understanding AJAX in Drupal

AJAX (Asynchronous JavaScript and XML) allows you to communicate with the server asynchronously, without interfering with the current page display. Drupal’s AJAX framework provides structured ways to implement this functionality through its API, offering both high-level abstractions and low-level control.

Implementing AJAX in Forms

AJAX in forms can enhance user interactivity by allowing form elements to dynamically update based on other selections. For example, a user selects an item from a dropdown, and another field updates its options based on that selection.

Example: AJAX in a Simple Form

We'll demonstrate using AJAX to update a textfield based on a dropdown selection using a simple form within the mymodule module.

Step 1: Define the Form

Create a form class in src/Form/AjaxExampleForm.php:



namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class AjaxExampleForm extends FormBase {

  public function getFormId() {
    return 'ajax_example_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['actions'] = [
      '#type' =--> 'actions',
    ];
    
    $form['dropdown'] = [
      '#type' => 'select',
      '#title' => $this->t('Select an option'),
      '#options' => [
        '1' => $this->t('Option 1'),
        '2' => $this->t('Option 2'),
      ],
      '#ajax' => [
        'callback' => '::updateTextfield',
        'wrapper' => 'textfield-wrapper',
      ],
    ];

    $form['textfield'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Updated Textfield'),
      '#prefix' => '',
      '#suffix' => '',
    ];

    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;
  }

  public function updateTextfield(array &$form, FormStateInterface $form_state) {
    $selected_value = $form_state->getValue('dropdown');
    $form['textfield']['#value'] = 'You selected: ' . $selected_value;
    return $form['textfield'];
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->messenger()->addMessage($this->t('Form has been submitted.'));
  }
}

Explanation:

In this form, the dropdown field triggers an AJAX call whenever its value changes, calling the updateTextfield() callback function. This function updates the textfield with the selected dropdown option, and the updated value is returned to the browser, dynamically updating the form.

Integrating AJAX in Controllers

AJAX can also be employed in custom controllers to dynamically update content on pages. Let's create a simple example that updates a content area when a button is clicked.

Example: AJAX in a Custom Controller

Step 1: Define the Controller

Create the controller file at src/Controller/AjaxExampleController.php:



namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

class AjaxExampleController extends ControllerBase {

  public function content() {
    $build = [
      '#markup' =--> 'This is some static content.',
      '#attached' => [
        'library' => [
          'core/drupal.ajax',
        ],
      ],
    ];

    $build['button'] = [
      '#type' => 'button',
      '#value' => $this->t('Update Content'),
      '#ajax' => [
        'callback' => '::updateContent',
        'wrapper' => 'ajax-content',
      ],
    ];

    return $build;
  }

  public function updateContent(array &$form, FormStateInterface $form_state) {
    return [ '#markup' => 'Content updated via AJAX.' ];
  }

}

Explanation:

This controller renders initial static content and a button. When the button is clicked, the AJAX system triggers the updateContent() method, updating the content of the targeted div with new information.

Testing Your AJAX Implementation

To see these examples in action, ensure your module is enabled, and navigate to your custom form and controller routes. Verify that selecting options or clicking buttons result in dynamic updates without a full-page reload.

Conclusion

By incorporating AJAX, you've enhanced your Drupal modules with powerful, user-friendly interactivity. AJAX will not only improve the end-user experience but will also prepare your modules for more complex and real-time data interactions.

In the next lesson, we'll continue our exploration of AJAX with a focus on using Drupal’s AJAX command system, which provides advanced capabilities for customizing AJAX responses. Join us to take your Drupal development to the next level!