Using Drupal’s AJAX command systemfor Drupal 8 , 9 , 10 , and 11

Last updated :  

Introduction

In previous lessons, we explored basic AJAX integration in Drupal forms and controllers. For developers looking to unlock more powerful and customized AJAX interactions, Drupal provides an AJAX command system. This system facilitates a fine-tuned control over server responses, enabling a greater diversity of client-side effects without full-page reloads.

Understanding Drupal's AJAX Command System

Drupal's AJAX command system is a flexible technique that allows developers to send a structured array of commands from the server to the client. Each command specifies a particular operation, such as updating page content, adding CSS classes, or triggering JavaScript alerts.

Core AJAX Commands in Drupal:

  • appendCommand: Appends new content to a specified page element.
  • replaceCommand: Replaces existing content within a specified page element.
  • removeCommand: Removes a specified page element.
  • alertCommand: Triggers a JavaScript alert.
  • settingsCommand: Updates Drupal JavaScript settings.

Implementing AJAX Commands in Drupal

We'll create a simple example where various AJAX commands update a page element. This demonstration will take place in a custom controller and build upon our mymodule from previous lessons.

Step 1: Define the Controller and Route

Start by defining the route and controller. Add the following to mymodule.routing.yml:


mymodule.ajax_example:
  path: '/ajax-example'
  defaults:
    _controller: '\Drupal\mymodule\Controller\AjaxCommandExample::content'
    _title: 'AJAX Command Example'
  requirements:
    _permission: 'access content'

Next, define the controller in src/Controller/AjaxCommandExample.php:



namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Ajax\AppendCommand;
use Drupal\Core\Ajax\AlertCommand;

class AjaxCommandExample extends ControllerBase {

  public function content() {
    $build = [
      '#markup' =--> 'Original Content Here',
      '#attached' => [
        'library' => [
          'core/drupal.ajax',
        ],
      ],
    ];

    $build['#attached']['drupalSettings']['myModuleAjax'] = TRUE;

    return $build;
  }

  public function ajaxResponse() {
    // Define an AjaxResponse object to hold commands.
    $response = new AjaxResponse();

    // Replace existing content in the target div.
    $response->addCommand(new ReplaceCommand('#ajax-command-content', 'New AJAX-replaced content here.'));

    // Append new content to the target div.
    $response->addCommand(new AppendCommand('#ajax-command-content', 'Additional content appended.'));

    // Trigger a JavaScript alert.
    $response->addCommand(new AlertCommand('This is an AJAX triggered alert!'));

    return $response;
  }
}

Explanation:

The ajaxResponse() method constructs an AjaxResponse object, adding three commands to demonstrate replacing, appending, and alerting. Each command manipulates a page element or triggers a notification.

Step 2: Add JavaScript to Trigger AJAX Request

To initiate an AJAX call, you'll need some JavaScript logic, typically placed in a custom library. For this tutorial, add inline scripts directly:


(function ($, Drupal) {
  Drupal.behaviors.myModuleAjaxBehavior = {
    attach: function (context, settings) {
      $('#ajax-command-content', context).once('myModuleAjaxBehavior').click(function () {
        $.ajax({
          url: '/ajax-example-command',
          type: 'POST',
          success: function (data) {
            Drupal.Ajax.prototype.success(data);
          }
        });
      });
    }
  };
})(jQuery, Drupal);

Explanation:

This script binds an AJAX call to the element with ID #ajax-command-content, triggering upon a click event. When clicked, it fetches an AJAX response from the specified path and executes the commands included.

Testing Your Implementation

Ensure your module is enabled and try out the AJAX feature:

  • Access the route /ajax-example.
  • Click the content to see the AJAX commands at work: content replacement, appending, and alert dialogs should occur.

Conclusion

Using Drupal's AJAX command system allows you to create rich, interactive experiences with finely-tuned server responses. By mastering these commands, you open up possibilities for more engaging and dynamic Drupal applications.

Next, we'll explore managing errors in AJAX responses to ensure robust and user-friendly interactions even when facing unexpected issues. Join us as we continue to explore advanced Drupal techniques!