Core AJAX Callback Commands

Last updated on
15 April 2025

This documentation needs review. See "Help improve this page" in the sidebar.

This page is based on "All classes that implement CommandInterface" and intends to give more definition to what each of these classes does. Most of this information is found on the pages for the respective commands, the goal here is to bring it into one location.

  • Unless specified otherwise the namespace is Drupal\Core\Ajax.
  • For example, unless specified otherwise, assumes you have appropriately placed the following in your code.
    • Typically this will be inside an AjaxCallback function
    • use Drupal\Core\Ajax\AjaxResponse;
    • $response = new AjaxResponse();

AddCssCommand

An AJAX command for adding CSS to the page via ajax. Unlike CssCommand which takes an array, AddCssCommand requires a string as argument.

This command is implemented by Drupal.AjaxCommands.prototype.add_css() defined in misc/ajax.js.

Example:

// A string that contains the styles to be added to the page, including the wrapping <style> tag.
$cssString = '<style>.myclass{color:red;}</style>'; 
$response->addCommand(new AddCssCommand($CssString));

AfterCommand*

An AJAX command for calling the jQuery after() method.

The 'insert/after' command instructs the client to use jQuery's after() method to insert the given HTML content after each element matched by the given selector.

This command is implemented by Drupal.AjaxCommands.prototype.insert() defined in misc/ajax.js.

Example:

// See: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors.
$selector = '.myclass'; 
// The content that will be inserted in the matched element(s), either a render array or an HTML string.
$content = '<p>my html content</p>';
// (Optional) An array of JavaScript settings to be passed to any attached behaviors.
$settings = ['my-setting' => 'setting',];

$response->addCommand(new AfterCommand($selector, $content, $settings));

AlertCommand

AJAX command for a javascript alert box.

Example:

// A string that contains the text to display as a JavaScript alert.
$text = 'My Text';
$response->addCommand(new AlertCommand($text));

AnnounceCommand

AJAX command for a JavaScript Drupal.announce() call.

Example:

// A string that contains the text to be announced by a screen reader.
$text = 'My Text';
// (optional) The priority that will be used for the announcement. Defaults to NULL which will not set a 'priority' in the response sent to the client and therefore the JavaScript Drupal.announce() default of 'polite' will be used for the message. Options: 'off','polite','assertive'. See https://www.w3.org/TR/wai-aria-1.1/#aria-live .
$priority = 'assertive';

$response->addCommand(new AnnounceCommand($text, $priority));

AppendCommand*

An AJAX command for calling the jQuery append() method.

The 'insert/append' command instructs the client to use jQuery's append() method to append the given HTML content to the inside of each element matched by the given selector.

This command is implemented by Drupal.AjaxCommands.prototype.insert() defined in misc/ajax.js.

Example:

// See: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors .
$selector = '.myclass';
// The content that will be inserted in the matched element(s), either a render array or an HTML string.
$content = '<p>my html content</p>';
// (Optional) An array of JavaScript settings to be passed to any attached behaviors.
$settings = ['my-setting' => 'setting',]; 

$response->addCommand(new AppendCommand($selector, $content, $settings));

BaseCommand

Base command only exists to simplify AJAX commands. NOT NORMALLY USED.

BeforeCommand*

An AJAX command for calling the jQuery before() method.

The 'insert/before' command instructs the client to use jQuery's before() method to insert the given HTML content before each of the elements is matched by the given selector.

This command is implemented by Drupal.AjaxCommands.prototype.insert() defined in misc/ajax.js.

Example:

// See: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors .
$selector = '.myclass'; 
// The content that will be inserted in the matched element(s), either a render array or an HTML string.
$content = '<p>my html content</p>'; 
// (Optional) An array of JavaScript settings to be passed to any attached behaviours.
$settings = ['my-setting' => 'setting',]; 

$response->addCommand(new BeforeCommand($selector, $content, $settings));

ChangedCommand

An AJAX command for marking HTML elements as changed.

This command instructs the client to mark each of the elements matched by the given selector as 'ajax-changed'.

This command is implemented by Drupal.AjaxCommands.prototype.changed() defined in misc/ajax.js.

Example:

// String: CSS selector for elements to be marked as changed.
$selector = '.myClass';
// (Optional) String: CSS selector for elements to which an asterisk will be appended.
$asterisk = '.myOtherClass';

$response->addCommand(new ChangedCommand($selector, $asterisk));

CloseDialogCommand

Defines an AJAX command that closes the currently active dialog.

Example:

// A CSS selector string of the dialog to close.
$selector = '#myID';
// (optional) Boolean: Whether to persist (store) the dialog in the DOM (true) or completely remove it(false).
$persist = FALSE;

$response->addCommand(new CloseDialogCommand($selector, $persist));

CloseModalDialogCommand

Defines an AJAX command that closes the currently visible modal dialog.

Example:

// (optional) Boolean: Whether to persist (store) the dialog in the DOM (true) or completely reomve it(false).
$persist = FALSE;
$response->addCommand(new CloseModalDialogCommand($persist));

CssCommand

An AJAX command for calling the jQuery css() method. Unlike AddCssCommand which takes a string, CssCommand requires an array of property/value pairs.

The 'CSS' command will instruct the client to use the jQuery css() method to apply the CSS arguments to elements matched by the given selector.

This command is implemented by Drupal.AjaxCommands.prototype.css() defined in misc/ajax.js.

Example:

// A CSS selector for elements to which the CSS will be applied.
$selector='#myID';
// An array of CSS property/value pairs to set.
$css = ['color' => 'red', 'vertical-align' => 'text-top'];

$response->addCommand(new CssCommand($selector, $css));

DataCommand

An AJAX command for implementing jQuery's data() method.

This instructs the client to attach the name=value pair of data to the selector via jQuery's data cache.

This command is implemented by Drupal.AjaxCommands.prototype.data() defined in misc/ajax.js.

Example:

// A CSS selector for the elements to which the data will be attached.
$selector = '#myID';
// The key of the data to be attached to elements matched by the selector.
$key = 'myKey'
// The value of the data to be attached to elements matched by the selector. Any data type convertible to JavaScript. See https://api.jquery.com/data/.
$value = ['some', 'set' => 'of', 'values'];

$response->addCommand(new DataCommand($selector, $key, $value));

HtmlCommand

AJAX command for calling the jQuery html() method.

The 'insert/html' command instructs the client to use jQuery's html() method to set the HTML content of each element matched by the given selector while leaving the outer tags intact.

This command is implemented by Drupal.AjaxCommands.prototype.insert() defined in misc/ajax.js.

Example:

// See: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors .
$Selector = '.myclass';
// The content that will be inserted in the matched element(s), either a render array or an HTML string.
$content = '<p>my html content</p>';
// (Optional) An array of JavaScript settings to be passed to any attached behaviours.
$settings = ['my-setting' => 'setting',]; 

$response->addCommand(new HtmlCommand($Selector, $content, $settings));

InsertCommand*

Generic AJAX command for inserting content. For most situations, it is better to use BeforeCommand, AfterCommand, AppendCommand, PrependCommand, HtmlCommand, or ReplaceCommand. This function exists for advanced manipulation.

This command instructs the client to insert the given HTML using whichever jQuery DOM manipulation method has been specified in the #ajax['method'] variable of the element that triggered the request.

This command is implemented by Drupal.AjaxCommands.prototype.insert() defined in misc/ajax.js.

Example:

// See: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors .
$selector = '.myclass';
// The content that will be inserted in the matched element(s), either a render array or an HTML string.
$content = '<p>my html content</p>';
// An array of JavaScript settings to be passed to any attached behaviours.
$settings = ['my-setting' => 'setting',];

$response->addCommand(new InsertCommand($selector, $content, $settings));

InvokeCommand

AJAX command for invoking an arbitrary jQuery method.

The 'invoke' command will instruct the client to invoke the given jQuery method with the supplied arguments on the elements matched by the given selector. Intended for simple jQuery commands, such as attr(), addClass(), removeClass(), toggleClass(), etc.

This command is implemented by Drupal.AjaxCommands.prototype.invoke() defined in misc/ajax.js.

// A jQuery selector.
$selector = '.myClass[name$="myNameSuffix"]';
// The name of a jQuery method to invoke.
$method = 'addClass';
// (Optional) An array of arguments to pass to the method.
$arguments = ['class1', 'class2'];

$response->addCommand(new InvokeCommand($selector, $method, $arguments));

MessageCommand

Specific version(s)

Introduced in version: 8.7.0

AJAX command that allows you to add messages from an Ajax response. The command will create a  new Drupal.Message() object and call its addMessage() method.

Example:

$response = new AjaxResponse();

// A status message added in the default location.
$response->addCommand(new MessageCommand('Your changes have been saved.'));

// A warning message added in the default location.
$response->addCommand(new MessageCommand('There was a problem. Please save your work and go outside.', NULL, ['type' => 'warning']));

// A status message added an alternate location.
$response->addCommand(new MessageCommand('Hey look over here!', '#alternate-message-container'));

// An error added in an alternate location.
$response->addCommand(new MessageCommand('Open the pod bay doors, HAL.',  '#alternate-message-container', ['type' => 'error']));

By default, previous messages in a location are cleared before the message is added. If you would like to leave the previous messages in a location, you may do so by setting the fourth parameter to FALSE:

$response->addCommand(new MessageCommand('Hey look over here.', NULL, ['type' => 'error'], FALSE));

Integration with Drupal.Announce() for screen readers

Developers should take care when using MessageCommand and AnnounceCommand together in the same AJAX response. Unless the "announce" option is set to an empty string (''), this command will result in the message being announced to screen readers. When combined with AnnounceCommand, this may result in unexpected behavior. Manual testing with a screen reader is strongly recommended.

If you wish to display a message without the text being announced to screen readers, add options.announce = '' (i.e. an empty string).

$response->addCommand(new MessageCommand('Your score is now 8675309!',  NULL, [ 
  'announce' => '',
]));

If you wish to set the announcement priority to assertive, you can do that this way: 

$response->addCommand(new MessageCommand('You added 3 cat pics.', '.js-media-library-messages', [
  'priority' => 'assertive',
]));

OpenDialogCommand

Defines an AJAX command to open certain content in a dialog.

Example:

// The selector of the dialog.
$selector = '#myID';
// The title of the dialog.
$title = 'Dialog Title';
// The content that will be placed in the dialog, either a render array or an HTML string.
$content = 'Some Content';
// (optional) Array of options to be passed to the dialog implementation. Any jQuery UI option can be used. See http://api.jqueryui.com/dialog.
$dialog_options = [
  'minHeight' => 200,
  'resizable' => TRUE
];

// (optional) Array of custom settings that will be passed to the Drupal behaviours on the content of the dialog. If left empty, the settings will be populated automatically from the current request. See https://www.drupal.org/docs/drupal-apis/javascript-api/javascript-api-overview.
$settings = [];

$response->addCommand(new OpenDialogCommand($selector, $title, $content, $dialog_options, $settings));

OpenModalDialogCommand

Defines an AJAX command to open certain content in a modal dialog.

Example:

// The title of the dialog.
$title = 'Dialog Title';
// The content that will be placed in the dialog, either a render array or an HTML string.
$content = 'Some Content';
// (optional) Array of options to be passed to the dialog implementation. Any jQuery UI option can be used. See http://api.jqueryui.com/dialog.
$dialog_options = [
  'minHeight' => 200, 
  'resizable' => TRUE
]; 
// (optional) Array of custom settings that will be passed to the Drupal behaviours on the content of the dialog. If left empty, the settings will be populated automatically from the current request. See https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview.
$settings= []; 

$response->addCommand(new OpenModalDialogCommand($title, $content, $dialog_options, $settings));

OpenOffCanvasDialogCommand

Defines an AJAX command to open content in a dialog in an off-canvas dialog.

Example:

// The title of the dialog.
$title = 'Dialog Title';

// The content that will be placed in the dialog, either a render array or an HTML string. 
$content = 'Some Content';

// (optional) Array of options to be passed to the dialog implementation. Any jQuery UI option can be used. See http://api.jqueryui.com/dialog.
$dialog_options = [
  'minHeight' => 200,
  'resizable' => TRUE
];

// (optional) Array of custom settings that will be passed to the Drupal behaviors on the content of the dialog. If left empty, the settings will be populated automatically from the current request. See https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview.
$settings = [];

// (optional) String showing the position to render the off-canvas dialog. See https://api.jqueryui.com/position/
$position = '{ my: "left top", at: "left bottom", of: button }';

$response->addCommand(new OpenOffCanvasDialogCommand($title, $content, $dialog_options, $settings, $position));

PrependCommand*

AJAX command for calling the jQuery insert() method.

The 'insert/prepend' command instructs the client to use jQuery's prepend() method to prepend the given HTML content to the inside each element matched by the given selector.

This command is implemented by Drupal.AjaxCommands.prototype.insert() defined in misc/ajax.js.

Example:

// See: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors.
$selector = '.myclass'; 

// The content that will be inserted in the matched element(s), either a render array or an HTML string.
$content = '<p>my htlm content</p>';

// (Optional) An array of JavaScript settings to be passed to any attached behaviors.
$settings = ['my-setting' => 'setting',];

$response->addCommand(new PrependCommand($selector, $content, $settings));

RedirectCommand

Defines an AJAX command to set the window.location, loading that URL.

Example:

// The URL that will be loaded into window.location. This should be a full URL.
$url='http://this.space.edu';
$response->addCommand(new RedirectCommand($url));

RemoveCommand

AJAX command for calling the jQuery remove() method.

The 'remove' command instructs the client to use jQuery's remove() method to remove each of the elements matched by the given selector, and everything within them.

This command is implemented by Drupal.AjaxCommands.prototype.remove() defined in misc/ajax.js.

Example:

$selector = '#myID'; /* CSS selector for item to remove. */
$response->addCommand(new RemoveCommand($selector));

ReplaceCommand

AJAX command for calling the jQuery replace() method.

The 'insert/replaceWith' command instructs the client to use jQuery's replaceWith() method to replace each element matched by the given selector with the given HTML.

This command is implemented by Drupal.AjaxCommands.prototype.insert() defined in misc/ajax.js.

Example:

// See: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors.
$selector = '.myclass';

// The content that will be replace the matched element(s), either a render array or an HTML string.
$content = '<p>my htlm content</p>';

// An array of JavaScript settings to be passed to any attached behaviors.
$settings = ['my-setting' => 'setting',];
$response->addCommand(new ReplaceCommand($selector, $content, $settings));

RestripeCommand

AJAX command for resetting the striping on a table.

The 'restripe' command instructs the client to restripe a table. This is usually used after a table has been modified by a replace or append command.

This command is implemented by Drupal.AjaxCommands.prototype.restripe() defined in misc/ajax.js.

Example:

// A CSS selector for the table to be restriped.
$selector = '#myTable';
$response->addCommand(new RestripeCommand($selector));

SetDialogOptionCommand

Defines an AJAX command that sets jQuery UI dialog properties.

Example:

// The selector of the dialog whose title will be set. If set to an empty value, the default modal dialog will be selected.
$selector = '#myDialog';
// The name of the option to set. May be any jQuery UI dialog option. See http://api.jqueryui.com/dialog. See https://api.jqueryui.com/dialog/
$option_name = 'autoOpen';
// The value of the option to be passed to the dialog.
$option_value = TRUE;

$response->addCommand(new SetDialogOptionCommand($selector, $option_name, $response));

SetDialogTitleCommand

Defines an AJAX command that sets jQuery UI dialog properties.

Example:

// The selector of the dialog whose title will be set. If set to an empty value, the default modal dialog will be selected.
$selector = '#myDialog';
// The title that will be set on the dialog.
$title = 'My New Title';

$response->addCommand(new SetDialogTitleCommand($selector, $option_name, $response));

SettingsCommand

AJAX command for adjusting Drupal's JavaScript settings.

The 'settings' command instructs the client either to use the given array as the settings for ajax-loaded content or to extend drupalSettings with the given array, depending on the value of the $merge parameter.

This command is implemented by Drupal.AjaxCommands.prototype.settings() defined in misc/ajax.js.

Example:

// An array of key/value pairs of JavaScript settings.
$settings = [
  'ajax_forms_test' => ['foo' => 42],
];

// (Optional) Booleen Whether the settings should be merged into the global drupalSettings.
$merge = TRUE;

$response->addCommand(new SettingsCommand($settings, $merge));

UpdateBuildIdCommand

AJAX command for updating the value of a hidden form_build_id input element on a form. It requires the form passed in to have keys for both the old build ID in #build_id_old and the new build ID in #build_id.

The primary use case for this Ajax command is to serve a new build ID to a form served from the cache to an anonymous user, preventing one anonymous user from accessing the form state of another anonymous user on Ajax-enabled forms.

This command is implemented by Drupal.AjaxCommands.prototype.update_build_id() defined in misc/ajax.js.

Example:

$old: /* The old form build_id. */
$new: /* The new form build_id. */
$response->addCommand(new UpdateBuildIDCommand($old, $new));

AddStyleSheetCommand

AJAX command to add style sheets to a CKEditor instance.

Example:

$editor_id: /* The Text Editor instance ID. */
$style_sheet: /* URL to the style sheet. */
$response->addCommand(new AddStyleSheetCommand($editor_id, $style_sheet));

OpenModalWizardCommand

Provided by ctools

EditorDialogSave

Provides an AJAX command for saving the contents of an editor dialog.

This command is implemented in editor.dialog.js in Drupal.AjaxCommands.prototype.editorDialogSave.

GetUntransformedTextCommand

AJAX command to rerender a formatted text field without any transformation filters.

JsAjaxTestCommand

Test Ajax command.

UpdateSelectionCommand

AJAX command for adding media items to the media library selection.

This command instructs the client to add the given media item IDs to the current selection of the media library stored in Drupal.MediaLibrary.currentSelection.

This command is implemented by Drupal.AjaxCommands.prototype.updateMediaLibrarySelection() defined in media_library.ui.js.

EntitySavedCommand

AJAX command to indicate the entity was loaded from PrivateTempStore and saved into the database.

FieldFormCommand

AJAX command for passing a rendered field form to Quick Edit's JavaScript app.

FieldFormSavedCommand

AJAX command to indicate a field was saved into PrivateTempStore without validation errors and pass the rerendered field to Quick Edit's JavaScript app.

FieldFormValidationErrorsCommand

AJAX command to indicate a field form was attempted to be saved but failed validation and pass the validation errors.

SetSubtreesCommand

Defines an AJAX command that sets the toolbar subtrees.

HighlightCommand

Provides an AJAX command for highlighting a certain new piece of HTML.

This command is implemented in Drupal.AjaxCommands.prototype.viewsHighlight.

ReplaceTitleCommand

Provides an AJAX command for replacing the page title.

This command is implemented in Drupal.AjaxCommands.prototype.viewsReplaceTitle.

ScrollTopCommand

Provides an AJAX command for scrolling to the top of an element.

This command is implemented in Drupal.AjaxCommands.prototype.viewsScrollTop.

ShowButtonsCommand

Provides an AJAX command for showing the save and cancel buttons.

This command is implemented in Drupal.AjaxCommands.prototype.viewsShowButtons.

TriggerPreviewCommand

Provides an AJAX command for triggering the views live preview.

This command is implemented in Drupal.AjaxCommands.prototype.viewsTriggerPreview.

SetFormCommand

Provides an AJAX command for setting a form to submit URL in modal forms.

This command is implemented in Drupal.AjaxCommands.prototype.viewsSetForm.

*This image shows the difference between Before, After, Prepend, and Append
Difference between Before, After, Prepend and Append

Help improve this page

Page status: Needs review

You can: