Drupal 8 AJAX

Below is a list and example of how to use the Ajax commands in Drupal 8.

Ajax Commands

<?php
/**
 * @file
 * List of ajax commands.
 */

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\AlertCommand;
use Drupal\Core\Ajax\InsertCommand;
use Drupal\Core\Ajax\AfterCommand;
use Drupal\Core\Ajax\BeforeCommand;
use Drupal\Core\Ajax\AppendCommand;
use Drupal\Core\Ajax\PrependCommand;
use Drupal\Core\Ajax\RemoveCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Ajax\InvokeCommand;
use Drupal\Core\Ajax\AddCssCommand;
use Drupal\Core\Ajax\DataCommand;
use Drupal\Core\Ajax\RedirectCommand;
use Drupal\Core\Ajax\ChangedCommand;
use Drupal\Core\Ajax\CloseDialogCommand;
use Drupal\Core\Ajax\RestripeCommand;
use Drupal\Core\Ajax\SettingsCommand;

/**
 * Class AjaxCommandList.
 */
class AjaxCommandList {

  /**
   * Command Examples.
   */
  public function commandExamples() {

    // JSON response object for AJAX requests.
    $response = new AjaxResponse();

    /**
     * AJAX command for a javascript alert box.
     *
     * @param string $text
     *   The text to be displayed in the alert box.
     */
    $response->addCommand(new AlertCommand($text));

    /**
     * Generic AJAX command for inserting content.
     *
     * @param string $selector
     *   A CSS selector.
     * @param string|array $content
     *   The content that will be inserted in the matched element(s), either a
     *   render array or an HTML string.
     * @param array $settings
     *   An array of JavaScript settings to be passed to any attached behaviors.
     */
    $response->addCommand(new InsertCommand($selector, $content, $settings));

    /**
     * AJAX command for calling the jQuery html() method.
     *
     * @params see InsertCommand()
     */
    $response->addCommand(new HtmlCommand($selector, $content, $settings));

    /**
     * An AJAX command for calling the jQuery after() method.
     *
     * @params see InsertCommand()
     */
    $response->addCommand(new AfterCommand($selector, $content, $settings));

    /**
     * An AJAX command for calling the jQuery before() method.
     *
     * @params see InsertCommand()
     */
    $response->addCommand(new BeforeCommand($selector, $content, $settings));

    /**
     * AJAX command for calling the jQuery html() method.
     *
     * @params see InsertCommand()
     */
    $response->addCommand(new ReplaceCommand($selector, $content, $settings));

    /**
     * An AJAX command for calling the jQuery append() method.
     *
     * @params see InsertCommand()
     */
    $response->addCommand(new AppendCommand($selector, $content, $settings));

    /**
     * AJAX command for calling the jQuery prepend() method.
     *
     * @params see InsertCommand()
     */
    $response->addCommand(new PrependCommand($selector, $content, $settings));

    /**
     * AJAX command for calling the jQuery remove() method.
     *
     * @param string $selector
     *   A CSS selector.
     */
    $response->addCommand(new RemoveCommand($selector));

    /**
     * AJAX command for invoking an arbitrary jQuery method.
     *
     * @param string $selector
     *   A jQuery selector.
     * @param string $method
     *   The name of a jQuery method to invoke.
     * @param array $arguments
     *   An optional array of arguments to pass to the method.
     */
    $response->addCommand(new InvokeCommand($selector, $method, $arguments));

    /**
     * An AJAX command for adding css to the page via ajax.
     *
     * @param string $styles
     *   A string that contains the styles to be added to the page, including the
     *   wrapping <style> tag.
     */
    $response->addCommand(new AddCssCommand($styles));

    /**
     * An AJAX command for implementing jQuery's data() method.
     *
     * @param string $selector
     *   A CSS selector for the elements to which the data will be attached.
     * @param string $name
     *   The key of the data to be attached to elements matched by the selector.
     * @param mixed $value
     *   The value of the data to be attached to elements matched by the selector.
     */
    $response->addCommand(new DataCommand($selector, $name, $value));

    /**
     * Defines an AJAX command to set the window.location, loading that URL.
     *
     * @param string $url
     *   The URL that will be loaded into window.location. This should be a full
     *   URL.
     */
    $response->addCommand(new RedirectCommand($url));

    /**
     * An AJAX command for marking HTML elements as changed.
     *
     * @param string $selector
     *   CSS selector for elements to be marked as changed.
     * @param string $asterisk
     *   CSS selector for elements to which an asterisk will be appended.
     */
    $response->addCommand(new ChangedCommand($selector, $asterisk));

    /**
     * AJAX command for resetting the striping on a table.
     *
     * @param string $selector
     *   A CSS selector for the table to be restriped.
     */
    $response->addCommand(new RestripeCommand($selector));

    /**
     * AJAX command for adjusting Drupal's JavaScript settings.
     *
     * @param array $settings
     *   An array of key/value pairs of JavaScript settings.
     * @param bool $merge
     *   Whether the settings should be merged into the global drupalSettings.
     */
    $response->addCommand(new SettingsCommand($settings, $merge));

    return $response;
  }

}

Invoke Command

Example below of triggering an event via the Invoke Command. First use add the InvokeCommand:

$response->addCommand(new InvokeCommand('html', 'trigger', array(
  'triggerName',
  array(
    'foo' => 'bar',
  ),
)));

Then add the below to your JS file:

  /**
   * Triggered by Invoke Command.
   */
  $(document).on('triggerName', function(e, data) {
    alert('data.foo'); // alerts string 'bar'
  });

Programmatically trigger the Ajax request

Below is an example of how to manually trigger an Ajax request. You will need to create a page that returns an Ajax Response of added commands and use that page URL in the settings below.


/**
 * @file
 * Example of how to programmatically trigger the Ajax request.
 */

(function ($, Drupal, drupalSettings) {

  'use strict';

  Drupal.behaviors.myCustomAJAXStuff = {
    attach: function (context) {

      var ajaxSettings = {
        url: 'my/url/path',
        // If the old version of Drupal.ajax() needs to be used those
        // properties can be added
        base: 'myBase',
        element: $(context).find('.someElement')
      };

      var myAjaxObject = Drupal.ajax(ajaxSettings);

      // Declare a new Ajax command specifically for this Ajax object.
      myAjaxObject.commands.insert = function (ajax, response, status) {
        $('#my-wrapper').append(response.data);
        alert('New content was appended to #my-wrapper');
      };

      // This command will remove this Ajax object from the page.
      myAjaxObject.commands.destroyObject = function (ajax, response, status) {
        Drupal.ajax.instances[this.instanceIndex] = null;
      };

      // Programmatically trigger the Ajax request.
      myAjaxObject.execute();
    }
  };
  
})(jQuery, Drupal, drupalSettings);