Overview for Drupal's Ajax API.
Ajax is the process of dynamically updating parts of a page's HTML based on data from the server. When a specified event takes place, a PHP callback is triggered, which performs server-side logic and may return updated markup or JavaScript commands to run. After the return, the browser runs the JavaScript or updates the markup on the fly, with no full page refresh necessary.
Many different events can trigger Ajax responses, including:
Forms that use the Drupal Form API (see the Form API topic for more information about forms) can trigger AJAX responses. Here is an outline of the steps:
See sections below for details on these two steps.
As an example of adding Ajax triggers to a form, consider editing a date format, where the user is provided with a sample of the generated date output as they type. To accomplish this, typing in the text field should trigger an Ajax response. This is done in the text field form array element in \Drupal\config_translation\FormElement\DateFormat::getFormElement():
'#ajax' => array( 'callback' => 'Drupal\config_translation\FormElement\DateFormat::ajaxSample', 'event' => 'keyup', 'progress' => array( 'type' => 'throbber', 'message' => NULL, ), ),
As you can see from this example, the #ajax property for a form element is an array. Here are the details of its elements, all of which are optional:
Once you have set up your form to trigger an Ajax response (see Adding Ajax triggers to a form above), you need to write some PHP code to process the response. If you use 'path' in your Ajax set-up, your route controller will be triggered with only the information you provide in the URL. If you use 'callback', your callback method is a function, which will receive the $form and $form_state from the triggering form. You can use $form_state to get information about the data the user has entered into the form. For instance, in the above example for the date format preview, \Drupal\config_translation\FormElement\DateFormat\ajaxSample() does this to get the format string entered by the user:
$format_value = \Drupal\Component\Utility\NestedArray::getValue( $form_state->getValues(), $form_state->getTriggeringElement()['#array_parents']);
Once you have processed the input, you have your choice of returning HTML markup or a set of Ajax commands. If you choose to return HTML markup, you can return it as a string or a renderable array, and it will be placed in the defined 'wrapper' element (see documentation above in Adding Ajax triggers to a form). In addition, any messages returned by drupal_get_messages(), themed as in status-messages.html.twig, will be prepended.
To return commands, you need to set up an object of class \Drupal\Core\Ajax\AjaxResponse, and then use its addCommand() method to add individual commands to it. In the date format preview example, the format output is calculated, and then it is returned as replacement markup for a div like this:
$response = new AjaxResponse(); $response->addCommand(new ReplaceCommand( '#edit-date-format-suffix', '<small id="edit-date-format-suffix">' . $format . '</small>')); return $response;
The individual commands that you can return implement interface \Drupal\Core\Ajax\CommandInterface. Available commands provide the ability to pop up alerts, manipulate text and markup in various ways, redirect to a new URL, and the generic \Drupal\Core\Ajax\InvokeCommand, which invokes an arbitrary jQuery command.
As noted above, status messages are prepended automatically if you use the 'wrapper' method and return HTML markup. This is not the case if you return commands, but if you would like to show status messages, you can add
array('#type' => 'status_messages')
to a render array, use drupal_render() to render it, and add a command to place the messages in an appropriate location.
Here are some additional methods you can use to trigger Ajax responses in Drupal:
Name | Location | Description |
---|---|---|
AddCssCommand | core/lib/Drupal/Core/Ajax/AddCssCommand.php | An AJAX command for adding css to the page via ajax. |
AfterCommand | core/lib/Drupal/Core/Ajax/AfterCommand.php | An AJAX command for calling the jQuery after() method. |
Ajax | core/lib/Drupal/Core/Render/Element/Ajax.php | Provides a render element for adding Ajax to a render element. |
AjaxResponse | core/lib/Drupal/Core/Ajax/AjaxResponse.php | JSON response object for AJAX requests. |
AlertCommand | core/lib/Drupal/Core/Ajax/AlertCommand.php | AJAX command for a javascript alert box. |
AppendCommand | core/lib/Drupal/Core/Ajax/AppendCommand.php | An AJAX command for calling the jQuery append() method. |
BeforeCommand | core/lib/Drupal/Core/Ajax/BeforeCommand.php | An AJAX command for calling the jQuery before() method. |
ChangedCommand | core/lib/Drupal/Core/Ajax/ChangedCommand.php | An AJAX command for marking HTML elements as changed. |
CloseDialogCommand | core/lib/Drupal/Core/Ajax/CloseDialogCommand.php | Defines an AJAX command that closes the current active dialog. |
CloseModalDialogCommand | core/lib/Drupal/Core/Ajax/CloseModalDialogCommand.php | Defines an AJAX command that closes the currently visible modal dialog. |
CssCommand | core/lib/Drupal/Core/Ajax/CssCommand.php | An AJAX command for calling the jQuery css() method. |
DataCommand | core/lib/Drupal/Core/Ajax/DataCommand.php | An AJAX command for implementing jQuery's data() method. |
HtmlCommand | core/lib/Drupal/Core/Ajax/HtmlCommand.php | AJAX command for calling the jQuery html() method. |
InsertCommand | core/lib/Drupal/Core/Ajax/InsertCommand.php | Generic AJAX command for inserting content. |
InvokeCommand | core/lib/Drupal/Core/Ajax/InvokeCommand.php | AJAX command for invoking an arbitrary jQuery method. |
OpenDialogCommand | core/lib/Drupal/Core/Ajax/OpenDialogCommand.php | Defines an AJAX command to open certain content in a dialog. |
OpenModalDialogCommand | core/lib/Drupal/Core/Ajax/OpenModalDialogCommand.php | Defines an AJAX command to open certain content in a dialog in a modal dialog. |
PrependCommand | core/lib/Drupal/Core/Ajax/PrependCommand.php | AJAX command for calling the jQuery insert() method. |
RedirectCommand | core/lib/Drupal/Core/Ajax/RedirectCommand.php | Defines an AJAX command to set the window.location, loading that URL. |
RemoveCommand | core/lib/Drupal/Core/Ajax/RemoveCommand.php | AJAX command for calling the jQuery remove() method. |
ReplaceCommand | core/lib/Drupal/Core/Ajax/ReplaceCommand.php | AJAX command for calling the jQuery replace() method. |
RestripeCommand | core/lib/Drupal/Core/Ajax/RestripeCommand.php | AJAX command for resetting the striping on a table. |
SetDialogOptionCommand | core/lib/Drupal/Core/Ajax/SetDialogOptionCommand.php | Defines an AJAX command that sets jQuery UI dialog properties. |
SetDialogTitleCommand | core/lib/Drupal/Core/Ajax/SetDialogTitleCommand.php | Defines an AJAX command that sets jQuery UI dialog properties. |
SettingsCommand | core/lib/Drupal/Core/Ajax/SettingsCommand.php | AJAX command for adjusting Drupal's JavaScript settings. |
UpdateBuildIdCommand | core/lib/Drupal/Core/Ajax/UpdateBuildIdCommand.php | 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. |
Name | Location | Description |
---|---|---|
CommandInterface | core/lib/Drupal/Core/Ajax/CommandInterface.php | AJAX command interface. |
CommandWithAttachedAssetsInterface | core/lib/Drupal/Core/Ajax/CommandWithAttachedAssetsInterface.php | Interface for Ajax commands that render content and attach assets. |
Name | Location | Description |
---|---|---|
CommandWithAttachedAssetsTrait | core/lib/Drupal/Core/Ajax/CommandWithAttachedAssetsTrait.php | Trait for Ajax commands that render content and attach assets. |
© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!core.api.php/group/ajax/8.1.x