3 * Provides Ajax page updating via jQuery $.ajax.
5 * Ajax is a method of making a request via JavaScript while viewing an HTML
6 * page. The request returns an array of commands encoded in JSON, which is
7 * then executed to make any changes that are necessary to the page.
9 * Drupal uses this file to enhance form elements with `#ajax['url']` and
10 * `#ajax['wrapper']` properties. If set, this file will automatically be
11 * included to provide Ajax capabilities.
14 (function($, window, Drupal, drupalSettings) {
16 * Attaches the Ajax behavior to each Ajax form element.
18 * @type {Drupal~behavior}
20 * @prop {Drupal~behaviorAttach} attach
21 * Initialize all {@link Drupal.Ajax} objects declared in
22 * `drupalSettings.ajax` or initialize {@link Drupal.Ajax} objects from
23 * DOM elements having the `use-ajax-submit` or `use-ajax` css class.
24 * @prop {Drupal~behaviorDetach} detach
25 * During `unload` remove all {@link Drupal.Ajax} objects related to
26 * the removed content.
28 Drupal.behaviors.AJAX = {
29 attach(context, settings) {
30 function loadAjaxBehavior(base) {
31 const elementSettings = settings.ajax[base];
32 if (typeof elementSettings.selector === 'undefined') {
33 elementSettings.selector = `#${base}`;
35 $(elementSettings.selector)
38 elementSettings.element = this;
39 elementSettings.base = base;
40 Drupal.ajax(elementSettings);
44 // Load all Ajax behaviors specified in the settings.
45 Object.keys(settings.ajax || {}).forEach(base => loadAjaxBehavior(base));
47 Drupal.ajax.bindAjaxLinks(document.body);
49 // This class means to submit the form to the action using Ajax.
53 const elementSettings = {};
55 // Ajax submits specified in this manner automatically submit to the
56 // normal form action.
57 elementSettings.url = $(this.form).attr('action');
58 // Form submit button clicks need to tell the form what was clicked so
59 // it gets passed in the POST request.
60 elementSettings.setClick = true;
61 // Form buttons use the 'click' event rather than mousedown.
62 elementSettings.event = 'click';
63 // Clicked form buttons look better with the throbber than the progress
65 elementSettings.progress = { type: 'throbber' };
66 elementSettings.base = $(this).attr('id');
67 elementSettings.element = this;
69 Drupal.ajax(elementSettings);
73 detach(context, settings, trigger) {
74 if (trigger === 'unload') {
75 Drupal.ajax.expired().forEach(instance => {
76 // Set this to null and allow garbage collection to reclaim
78 Drupal.ajax.instances[instance.instanceIndex] = null;
85 * Extends Error to provide handling for Errors in Ajax.
91 * @param {XMLHttpRequest} xmlhttp
92 * XMLHttpRequest object used for the failed request.
94 * The URI where the error occurred.
95 * @param {string} customMessage
98 Drupal.AjaxError = function(xmlhttp, uri, customMessage) {
102 if (xmlhttp.status) {
103 statusCode = `\n${Drupal.t('An AJAX HTTP error occurred.')}\n${Drupal.t(
104 'HTTP Result Code: !status',
105 { '!status': xmlhttp.status },
108 statusCode = `\n${Drupal.t(
109 'An AJAX HTTP request terminated abnormally.',
112 statusCode += `\n${Drupal.t('Debugging information follows.')}`;
113 const pathText = `\n${Drupal.t('Path: !uri', { '!uri': uri })}`;
115 // In some cases, when statusCode === 0, xmlhttp.statusText may not be
116 // defined. Unfortunately, testing for it with typeof, etc, doesn't seem to
117 // catch that and the test causes an exception. So we need to catch the
120 statusText = `\n${Drupal.t('StatusText: !statusText', {
121 '!statusText': $.trim(xmlhttp.statusText),
128 // Again, we don't have a way to know for sure whether accessing
129 // xmlhttp.responseText is going to throw an exception. So we'll catch it.
131 responseText = `\n${Drupal.t('ResponseText: !responseText', {
132 '!responseText': $.trim(xmlhttp.responseText),
138 // Make the responseText more readable by stripping HTML tags and newlines.
139 responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi, '');
140 responseText = responseText.replace(/[\n]+\s+/g, '\n');
142 // We don't need readyState except for status == 0.
143 const readyStateText =
145 ? `\n${Drupal.t('ReadyState: !readyState', {
146 '!readyState': xmlhttp.readyState,
150 customMessage = customMessage
151 ? `\n${Drupal.t('CustomMessage: !customMessage', {
152 '!customMessage': customMessage,
157 * Formatted and translated error message.
170 * Used by some browsers to display a more accurate stack trace.
174 this.name = 'AjaxError';
177 Drupal.AjaxError.prototype = new Error();
178 Drupal.AjaxError.prototype.constructor = Drupal.AjaxError;
181 * Provides Ajax page updating via jQuery $.ajax.
183 * This function is designed to improve developer experience by wrapping the
184 * initialization of {@link Drupal.Ajax} objects and storing all created
185 * objects in the {@link Drupal.ajax.instances} array.
188 * Drupal.behaviors.myCustomAJAXStuff = {
189 * attach: function (context, settings) {
191 * var ajaxSettings = {
192 * url: 'my/url/path',
193 * // If the old version of Drupal.ajax() needs to be used those
194 * // properties can be added
196 * element: $(context).find('.someElement')
199 * var myAjaxObject = Drupal.ajax(ajaxSettings);
201 * // Declare a new Ajax command specifically for this Ajax object.
202 * myAjaxObject.commands.insert = function (ajax, response, status) {
203 * $('#my-wrapper').append(response.data);
204 * alert('New content was appended to #my-wrapper');
207 * // This command will remove this Ajax object from the page.
208 * myAjaxObject.commands.destroyObject = function (ajax, response, status) {
209 * Drupal.ajax.instances[this.instanceIndex] = null;
212 * // Programmatically trigger the Ajax request.
213 * myAjaxObject.execute();
217 * @param {object} settings
218 * The settings object passed to {@link Drupal.Ajax} constructor.
219 * @param {string} [settings.base]
220 * Base is passed to {@link Drupal.Ajax} constructor as the 'base'
222 * @param {HTMLElement} [settings.element]
223 * Element parameter of {@link Drupal.Ajax} constructor, element on which
224 * event listeners will be bound.
226 * @return {Drupal.Ajax}
227 * The created Ajax object.
229 * @see Drupal.AjaxCommands
231 Drupal.ajax = function(settings) {
232 if (arguments.length !== 1) {
234 'Drupal.ajax() function must be called with one configuration object only',
237 // Map those config keys to variables for the old Drupal.ajax function.
238 const base = settings.base || false;
239 const element = settings.element || false;
240 delete settings.base;
241 delete settings.element;
243 // By default do not display progress for ajax calls without an element.
244 if (!settings.progress && !element) {
245 settings.progress = false;
248 const ajax = new Drupal.Ajax(base, element, settings);
249 ajax.instanceIndex = Drupal.ajax.instances.length;
250 Drupal.ajax.instances.push(ajax);
256 * Contains all created Ajax objects.
258 * @type {Array.<Drupal.Ajax|null>}
260 Drupal.ajax.instances = [];
263 * List all objects where the associated element is not in the DOM
265 * This method ignores {@link Drupal.Ajax} objects not bound to DOM elements
266 * when created with {@link Drupal.ajax}.
268 * @return {Array.<Drupal.Ajax>}
269 * The list of expired {@link Drupal.Ajax} objects.
271 Drupal.ajax.expired = function() {
272 return Drupal.ajax.instances.filter(
275 instance.element !== false &&
276 !document.body.contains(instance.element),
281 * Bind Ajax functionality to links that use the 'use-ajax' class.
283 * @param {HTMLElement} element
284 * Element to enable Ajax functionality for.
286 Drupal.ajax.bindAjaxLinks = element => {
287 // Bind Ajax behaviors to all items showing the class.
291 .each((i, ajaxLink) => {
292 const $linkElement = $(ajaxLink);
294 const elementSettings = {
295 // Clicked links look better with the throbber than the progress bar.
296 progress: { type: 'throbber' },
297 dialogType: $linkElement.data('dialog-type'),
298 dialog: $linkElement.data('dialog-options'),
299 dialogRenderer: $linkElement.data('dialog-renderer'),
300 base: $linkElement.attr('id'),
303 const href = $linkElement.attr('href');
305 * For anchor tags, these will go to the target of the anchor rather
306 * than the usual location.
309 elementSettings.url = href;
310 elementSettings.event = 'click';
312 Drupal.ajax(elementSettings);
317 * Settings for an Ajax object.
319 * @typedef {object} Drupal.Ajax~elementSettings
322 * Target of the Ajax request.
323 * @prop {?string} [event]
324 * Event bound to settings.element which will trigger the Ajax request.
325 * @prop {bool} [keypress=true]
326 * Triggers a request on keypress events.
327 * @prop {?string} selector
328 * jQuery selector targeting the element to bind events to or used with
329 * {@link Drupal.AjaxCommands}.
330 * @prop {string} [effect='none']
331 * Name of the jQuery method to use for displaying new Ajax content.
332 * @prop {string|number} [speed='none']
333 * Speed with which to apply the effect.
334 * @prop {string} [method]
335 * Name of the jQuery method used to insert new content in the targeted
337 * @prop {object} [progress]
338 * Settings for the display of a user-friendly loader.
339 * @prop {string} [progress.type='throbber']
340 * Type of progress element, core provides `'bar'`, `'throbber'` and
342 * @prop {string} [progress.message=Drupal.t('Please wait...')]
343 * Custom message to be used with the bar indicator.
344 * @prop {object} [submit]
345 * Extra data to be sent with the Ajax request.
346 * @prop {bool} [submit.js=true]
347 * Allows the PHP side to know this comes from an Ajax request.
348 * @prop {object} [dialog]
349 * Options for {@link Drupal.dialog}.
350 * @prop {string} [dialogType]
351 * One of `'modal'` or `'dialog'`.
352 * @prop {string} [prevent]
353 * List of events on which to stop default action and stop propagation.
359 * The Ajax request returns an array of commands encoded in JSON, which is
360 * then executed to make any changes that are necessary to the page.
362 * Drupal uses this file to enhance form elements with `#ajax['url']` and
363 * `#ajax['wrapper']` properties. If set, this file will automatically be
364 * included to provide Ajax capabilities.
368 * @param {string} [base]
369 * Base parameter of {@link Drupal.Ajax} constructor
370 * @param {HTMLElement} [element]
371 * Element parameter of {@link Drupal.Ajax} constructor, element on which
372 * event listeners will be bound.
373 * @param {Drupal.Ajax~elementSettings} elementSettings
374 * Settings for this Ajax object.
376 Drupal.Ajax = function(base, element, elementSettings) {
378 event: element ? 'mousedown' : null,
380 selector: base ? `#${base}` : null,
383 method: 'replaceWith',
386 message: Drupal.t('Please wait...'),
393 $.extend(this, defaults, elementSettings);
396 * @type {Drupal.AjaxCommands}
398 this.commands = new Drupal.AjaxCommands();
401 * @type {bool|number}
403 this.instanceIndex = false;
405 // @todo Remove this after refactoring the PHP code to:
406 // - Call this 'selector'.
407 // - Include the '#' for ID-based selectors.
408 // - Support non-ID-based selectors.
413 this.wrapper = `#${this.wrapper}`;
417 * @type {HTMLElement}
419 this.element = element;
422 * @deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0.
423 * Use elementSettings.
425 * @type {Drupal.Ajax~elementSettings}
427 this.element_settings = elementSettings;
430 * @type {Drupal.Ajax~elementSettings}
432 this.elementSettings = elementSettings;
434 // If there isn't a form, jQuery.ajax() will be used instead, allowing us to
435 // bind Ajax to links as well.
436 if (this.element && this.element.form) {
440 this.$form = $(this.element.form);
443 // If no Ajax callback URL was given, use the link href or form action.
445 const $element = $(this.element);
446 if ($element.is('a')) {
447 this.url = $element.attr('href');
448 } else if (this.element && element.form) {
449 this.url = this.$form.attr('action');
453 // Replacing 'nojs' with 'ajax' in the URL allows for an easy method to let
454 // the server detect when it needs to degrade gracefully.
455 // There are four scenarios to check for:
457 // 2. /nojs$ - The end of a URL string.
458 // 3. /nojs? - Followed by a query (e.g. path/nojs?destination=foobar).
459 // 4. /nojs# - Followed by a fragment (e.g.: path/nojs#myfragment).
460 const originalUrl = this.url;
463 * Processed Ajax URL.
467 this.url = this.url.replace(/\/nojs(\/|$|\?|#)/, '/ajax$1');
468 // If the 'nojs' version of the URL is trusted, also trust the 'ajax'
470 if (drupalSettings.ajaxTrustedUrl[originalUrl]) {
471 drupalSettings.ajaxTrustedUrl[this.url] = true;
474 // Set the options for the ajaxSubmit function.
475 // The 'this' variable will not persist inside of the options object.
479 * Options for the jQuery.ajax function.
481 * @name Drupal.Ajax#options
486 * Ajax URL to be called.
487 * @prop {object} data
489 * @prop {function} beforeSerialize
490 * Implement jQuery beforeSerialize function to call
491 * {@link Drupal.Ajax#beforeSerialize}.
492 * @prop {function} beforeSubmit
493 * Implement jQuery beforeSubmit function to call
494 * {@link Drupal.Ajax#beforeSubmit}.
495 * @prop {function} beforeSend
496 * Implement jQuery beforeSend function to call
497 * {@link Drupal.Ajax#beforeSend}.
498 * @prop {function} success
499 * Implement jQuery success function to call
500 * {@link Drupal.Ajax#success}.
501 * @prop {function} complete
502 * Implement jQuery success function to clean up ajax state and trigger an
504 * @prop {string} dataType='json'
505 * Type of the response expected.
506 * @prop {string} type='POST'
507 * HTTP method to use for the Ajax request.
512 beforeSerialize(elementSettings, options) {
513 return ajax.beforeSerialize(elementSettings, options);
515 beforeSubmit(formValues, elementSettings, options) {
517 return ajax.beforeSubmit(formValues, elementSettings, options);
519 beforeSend(xmlhttprequest, options) {
521 return ajax.beforeSend(xmlhttprequest, options);
523 success(response, status, xmlhttprequest) {
524 // Sanity check for browser support (object expected).
525 // When using iFrame uploads, responses must be returned as a string.
526 if (typeof response === 'string') {
527 response = $.parseJSON(response);
530 // Prior to invoking the response's commands, verify that they can be
531 // trusted by checking for a response header. See
532 // \Drupal\Core\EventSubscriber\AjaxResponseSubscriber for details.
533 // - Empty responses are harmless so can bypass verification. This
534 // avoids an alert message for server-generated no-op responses that
535 // skip Ajax rendering.
536 // - Ajax objects with trusted URLs (e.g., ones defined server-side via
537 // #ajax) can bypass header verification. This is especially useful
538 // for Ajax with multipart forms. Because IFRAME transport is used,
539 // the response headers cannot be accessed for verification.
540 if (response !== null && !drupalSettings.ajaxTrustedUrl[ajax.url]) {
541 if (xmlhttprequest.getResponseHeader('X-Drupal-Ajax-Token') !== '1') {
542 const customMessage = Drupal.t(
543 'The response failed verification so will not be processed.',
545 return ajax.error(xmlhttprequest, ajax.url, customMessage);
549 return ajax.success(response, status);
551 complete(xmlhttprequest, status) {
552 ajax.ajaxing = false;
553 if (status === 'error' || status === 'parsererror') {
554 return ajax.error(xmlhttprequest, ajax.url);
561 if (elementSettings.dialog) {
562 ajax.options.data.dialogOptions = elementSettings.dialog;
565 // Ensure that we have a valid URL by adding ? when no query parameter is
566 // yet available, otherwise append using &.
567 if (ajax.options.url.indexOf('?') === -1) {
568 ajax.options.url += '?';
570 ajax.options.url += '&';
572 // If this element has a dialog type use if for the wrapper if not use 'ajax'.
573 let wrapper = `drupal_${elementSettings.dialogType || 'ajax'}`;
574 if (elementSettings.dialogRenderer) {
575 wrapper += `.${elementSettings.dialogRenderer}`;
577 ajax.options.url += `${Drupal.ajax.WRAPPER_FORMAT}=${wrapper}`;
579 // Bind the ajaxSubmit function to the element event.
580 $(ajax.element).on(elementSettings.event, function(event) {
582 !drupalSettings.ajaxTrustedUrl[ajax.url] &&
583 !Drupal.url.isLocal(ajax.url)
586 Drupal.t('The callback URL is not local and not trusted: !url', {
591 return ajax.eventResponse(this, event);
594 // If necessary, enable keyboard submission so that Ajax behaviors
595 // can be triggered through keyboard input as well as e.g. a mousedown
597 if (elementSettings.keypress) {
598 $(ajax.element).on('keypress', function(event) {
599 return ajax.keypressResponse(this, event);
603 // If necessary, prevent the browser default action of an additional event.
604 // For example, prevent the browser default action of a click, even if the
605 // Ajax behavior binds to mousedown.
606 if (elementSettings.prevent) {
607 $(ajax.element).on(elementSettings.prevent, false);
612 * URL query attribute to indicate the wrapper used to render a request.
614 * The wrapper format determines how the HTML is wrapped, for example in a
621 Drupal.ajax.WRAPPER_FORMAT = '_wrapper_format';
624 * Request parameter to indicate that a request is a Drupal Ajax request.
630 Drupal.Ajax.AJAX_REQUEST_PARAMETER = '_drupal_ajax';
633 * Execute the ajax request.
635 * Allows developers to execute an Ajax request manually without specifying
636 * an event to respond to.
639 * Returns the jQuery.Deferred object underlying the Ajax request. If
640 * pre-serialization fails, the Deferred will be returned in the rejected
643 Drupal.Ajax.prototype.execute = function() {
644 // Do not perform another ajax command if one is already in progress.
650 this.beforeSerialize(this.element, this.options);
651 // Return the jqXHR so that external code can hook into the Deferred API.
652 return $.ajax(this.options);
654 // Unset the ajax.ajaxing flag here because it won't be unset during
655 // the complete response.
656 this.ajaxing = false;
658 `An error occurred while attempting to process ${this.options.url}: ${
662 // For consistency, return a rejected Deferred (i.e., jqXHR's superclass)
663 // so that calling code can take appropriate action.
664 return $.Deferred().reject();
669 * Handle a key press.
671 * The Ajax object will, if instructed, bind to a key press response. This
672 * will test to see if the key press is valid to trigger this event and
673 * if it is, trigger it for us and prevent other keypresses from triggering.
674 * In this case we're handling RETURN and SPACEBAR keypresses (event codes 13
675 * and 32. RETURN is often used to submit a form when in a textfield, and
676 * SPACE is often used to activate an element without submitting.
678 * @param {HTMLElement} element
679 * Element the event was triggered on.
680 * @param {jQuery.Event} event
683 Drupal.Ajax.prototype.keypressResponse = function(element, event) {
684 // Create a synonym for this to reduce code confusion.
687 // Detect enter key and space bar and allow the standard response for them,
688 // except for form elements of type 'text', 'tel', 'number' and 'textarea',
689 // where the spacebar activation causes inappropriate activation if
690 // #ajax['keypress'] is TRUE. On a text-type widget a space should always
693 event.which === 13 ||
694 (event.which === 32 &&
695 element.type !== 'text' &&
696 element.type !== 'textarea' &&
697 element.type !== 'tel' &&
698 element.type !== 'number')
700 event.preventDefault();
701 event.stopPropagation();
702 $(element).trigger(ajax.elementSettings.event);
707 * Handle an event that triggers an Ajax response.
709 * When an event that triggers an Ajax response happens, this method will
710 * perform the actual Ajax call. It is bound to the event using
711 * bind() in the constructor, and it uses the options specified on the
714 * @param {HTMLElement} element
715 * Element the event was triggered on.
716 * @param {jQuery.Event} event
719 Drupal.Ajax.prototype.eventResponse = function(element, event) {
720 event.preventDefault();
721 event.stopPropagation();
723 // Create a synonym for this to reduce code confusion.
726 // Do not perform another Ajax command if one is already in progress.
733 // If setClick is set, we must set this to ensure that the button's
736 // Mark the clicked button. 'form.clk' is a special variable for
737 // ajaxSubmit that tells the system which element got clicked to
738 // trigger the submit. Without it there would be no 'op' or
740 element.form.clk = element;
743 ajax.$form.ajaxSubmit(ajax.options);
745 ajax.beforeSerialize(ajax.element, ajax.options);
746 $.ajax(ajax.options);
749 // Unset the ajax.ajaxing flag here because it won't be unset during
750 // the complete response.
751 ajax.ajaxing = false;
753 `An error occurred while attempting to process ${ajax.options.url}: ${
761 * Handler for the form serialization.
763 * Runs before the beforeSend() handler (see below), and unlike that one, runs
764 * before field data is collected.
766 * @param {object} [element]
767 * Ajax object's `elementSettings`.
768 * @param {object} options
769 * jQuery.ajax options.
771 Drupal.Ajax.prototype.beforeSerialize = function(element, options) {
772 // Allow detaching behaviors to update field values before collecting them.
773 // This is only needed when field values are added to the POST data, so only
774 // when there is a form such that this.$form.ajaxSubmit() is used instead of
775 // $.ajax(). When there is no form and $.ajax() is used, beforeSerialize()
776 // isn't called, but don't rely on that: explicitly check this.$form.
778 const settings = this.settings || drupalSettings;
779 Drupal.detachBehaviors(this.$form.get(0), settings, 'serialize');
782 // Inform Drupal that this is an AJAX request.
783 options.data[Drupal.Ajax.AJAX_REQUEST_PARAMETER] = 1;
785 // Allow Drupal to return new JavaScript and CSS files to load without
786 // returning the ones already loaded.
787 // @see \Drupal\Core\Theme\AjaxBasePageNegotiator
788 // @see \Drupal\Core\Asset\LibraryDependencyResolverInterface::getMinimalRepresentativeSubset()
789 // @see system_js_settings_alter()
790 const pageState = drupalSettings.ajaxPageState;
791 options.data['ajax_page_state[theme]'] = pageState.theme;
792 options.data['ajax_page_state[theme_token]'] = pageState.theme_token;
793 options.data['ajax_page_state[libraries]'] = pageState.libraries;
797 * Modify form values prior to form submission.
799 * @param {Array.<object>} formValues
800 * Processed form values.
801 * @param {jQuery} element
802 * The form node as a jQuery object.
803 * @param {object} options
804 * jQuery.ajax options.
806 Drupal.Ajax.prototype.beforeSubmit = function(formValues, element, options) {
807 // This function is left empty to make it simple to override for modules
808 // that wish to add functionality here.
812 * Prepare the Ajax request before it is sent.
814 * @param {XMLHttpRequest} xmlhttprequest
815 * Native Ajax object.
816 * @param {object} options
817 * jQuery.ajax options.
819 Drupal.Ajax.prototype.beforeSend = function(xmlhttprequest, options) {
820 // For forms without file inputs, the jQuery Form plugin serializes the
821 // form values, and then calls jQuery's $.ajax() function, which invokes
822 // this handler. In this circumstance, options.extraData is never used. For
823 // forms with file inputs, the jQuery Form plugin uses the browser's normal
824 // form submission mechanism, but captures the response in a hidden IFRAME.
825 // In this circumstance, it calls this handler first, and then appends
826 // hidden fields to the form to submit the values in options.extraData.
827 // There is no simple way to know which submission mechanism will be used,
828 // so we add to extraData regardless, and allow it to be ignored in the
831 options.extraData = options.extraData || {};
833 // Let the server know when the IFRAME submission mechanism is used. The
834 // server can use this information to wrap the JSON response in a
835 // TEXTAREA, as per http://jquery.malsup.com/form/#file-upload.
836 options.extraData.ajax_iframe_upload = '1';
838 // The triggering element is about to be disabled (see below), but if it
839 // contains a value (e.g., a checkbox, textfield, select, etc.), ensure
840 // that value is included in the submission. As per above, submissions
841 // that use $.ajax() are already serialized prior to the element being
842 // disabled, so this is only needed for IFRAME submissions.
843 const v = $.fieldValue(this.element);
845 options.extraData[this.element.name] = v;
849 // Disable the element that received the change to prevent user interface
850 // interaction while the Ajax request is in progress. ajax.ajaxing prevents
851 // the element from triggering a new request, but does not prevent the user
852 // from changing its value.
853 $(this.element).prop('disabled', true);
855 if (!this.progress || !this.progress.type) {
859 // Insert progress indicator.
860 const progressIndicatorMethod = `setProgressIndicator${this.progress.type
862 .toUpperCase()}${this.progress.type.slice(1).toLowerCase()}`;
864 progressIndicatorMethod in this &&
865 typeof this[progressIndicatorMethod] === 'function'
867 this[progressIndicatorMethod].call(this);
872 * An animated progress throbber and container element for AJAX operations.
874 * @param {string} [message]
875 * (optional) The message shown on the UI.
877 * The HTML markup for the throbber.
879 Drupal.theme.ajaxProgressThrobber = message => {
880 // Build markup without adding extra white space since it affects rendering.
881 const messageMarkup =
882 typeof message === 'string'
883 ? Drupal.theme('ajaxProgressMessage', message)
885 const throbber = '<div class="throbber"> </div>';
887 return `<div class="ajax-progress ajax-progress-throbber">${throbber}${messageMarkup}</div>`;
891 * An animated progress throbber and container element for AJAX operations.
894 * The HTML markup for the throbber.
896 Drupal.theme.ajaxProgressIndicatorFullscreen = () =>
897 '<div class="ajax-progress ajax-progress-fullscreen"> </div>';
900 * Formats text accompanying the AJAX progress throbber.
902 * @param {string} message
903 * The message shown on the UI.
905 * The HTML markup for the throbber.
907 Drupal.theme.ajaxProgressMessage = message =>
908 `<div class="message">${message}</div>`;
911 * Sets the progress bar progress indicator.
913 Drupal.Ajax.prototype.setProgressIndicatorBar = function() {
914 const progressBar = new Drupal.ProgressBar(
915 `ajax-progress-${this.element.id}`,
917 this.progress.method,
920 if (this.progress.message) {
921 progressBar.setProgress(-1, this.progress.message);
923 if (this.progress.url) {
924 progressBar.startMonitoring(
926 this.progress.interval || 1500,
929 this.progress.element = $(progressBar.element).addClass(
930 'ajax-progress ajax-progress-bar',
932 this.progress.object = progressBar;
933 $(this.element).after(this.progress.element);
937 * Sets the throbber progress indicator.
939 Drupal.Ajax.prototype.setProgressIndicatorThrobber = function() {
940 this.progress.element = $(
941 Drupal.theme('ajaxProgressThrobber', this.progress.message),
943 $(this.element).after(this.progress.element);
947 * Sets the fullscreen progress indicator.
949 Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function() {
950 this.progress.element = $(Drupal.theme('ajaxProgressIndicatorFullscreen'));
951 $('body').after(this.progress.element);
955 * Handler for the form redirection completion.
957 * @param {Array.<Drupal.AjaxCommands~commandDefinition>} response
958 * Drupal Ajax response.
959 * @param {number} status
960 * XMLHttpRequest status.
962 Drupal.Ajax.prototype.success = function(response, status) {
963 // Remove the progress element.
964 if (this.progress.element) {
965 $(this.progress.element).remove();
967 if (this.progress.object) {
968 this.progress.object.stopMonitoring();
970 $(this.element).prop('disabled', false);
972 // Save element's ancestors tree so if the element is removed from the dom
973 // we can try to refocus one of its parents. Using addBack reverse the
974 // result array, meaning that index 0 is the highest parent in the hierarchy
975 // in this situation it is usually a <form> element.
976 const elementParents = $(this.element)
977 .parents('[data-drupal-selector]')
981 // Track if any command is altering the focus so we can avoid changing the
982 // focus set by the Ajax command.
983 let focusChanged = false;
984 Object.keys(response || {}).forEach(i => {
985 if (response[i].command && this.commands[response[i].command]) {
986 this.commands[response[i].command](this, response[i], status);
988 response[i].command === 'invoke' &&
989 response[i].method === 'focus'
996 // If the focus hasn't be changed by the ajax commands, try to refocus the
997 // triggering element or one of its parents if that element does not exist
1002 !$(this.element).data('disable-refocus')
1006 for (let n = elementParents.length - 1; !target && n >= 0; n--) {
1007 target = document.querySelector(
1008 `[data-drupal-selector="${elementParents[n].getAttribute(
1009 'data-drupal-selector',
1015 $(target).trigger('focus');
1019 // Reattach behaviors, if they were detached in beforeSerialize(). The
1020 // attachBehaviors() called on the new content from processing the response
1021 // commands is not sufficient, because behaviors from the entire form need
1022 // to be reattached.
1024 const settings = this.settings || drupalSettings;
1025 Drupal.attachBehaviors(this.$form.get(0), settings);
1028 // Remove any response-specific settings so they don't get used on the next
1030 this.settings = null;
1034 * Build an effect object to apply an effect when adding new HTML.
1036 * @param {object} response
1037 * Drupal Ajax response.
1038 * @param {string} [response.effect]
1039 * Override the default value of {@link Drupal.Ajax#elementSettings}.
1040 * @param {string|number} [response.speed]
1041 * Override the default value of {@link Drupal.Ajax#elementSettings}.
1044 * Returns an object with `showEffect`, `hideEffect` and `showSpeed`
1047 Drupal.Ajax.prototype.getEffect = function(response) {
1048 const type = response.effect || this.effect;
1049 const speed = response.speed || this.speed;
1052 if (type === 'none') {
1053 effect.showEffect = 'show';
1054 effect.hideEffect = 'hide';
1055 effect.showSpeed = '';
1056 } else if (type === 'fade') {
1057 effect.showEffect = 'fadeIn';
1058 effect.hideEffect = 'fadeOut';
1059 effect.showSpeed = speed;
1061 effect.showEffect = `${type}Toggle`;
1062 effect.hideEffect = `${type}Toggle`;
1063 effect.showSpeed = speed;
1070 * Handler for the form redirection error.
1072 * @param {object} xmlhttprequest
1073 * Native XMLHttpRequest object.
1074 * @param {string} uri
1076 * @param {string} [customMessage]
1077 * Extra message to print with the Ajax error.
1079 Drupal.Ajax.prototype.error = function(xmlhttprequest, uri, customMessage) {
1080 // Remove the progress element.
1081 if (this.progress.element) {
1082 $(this.progress.element).remove();
1084 if (this.progress.object) {
1085 this.progress.object.stopMonitoring();
1088 $(this.wrapper).show();
1089 // Re-enable the element.
1090 $(this.element).prop('disabled', false);
1091 // Reattach behaviors, if they were detached in beforeSerialize().
1093 const settings = this.settings || drupalSettings;
1094 Drupal.attachBehaviors(this.$form.get(0), settings);
1096 throw new Drupal.AjaxError(xmlhttprequest, uri, customMessage);
1100 * Provide a wrapper for new content via Ajax.
1102 * Wrap the inserted markup when inserting multiple root elements with an
1105 * @param {jQuery} $newContent
1106 * Response elements after parsing.
1107 * @param {Drupal.Ajax} ajax
1108 * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1109 * @param {object} response
1110 * The response from the Ajax request.
1112 * @deprecated in Drupal 8.6.x and will be removed before Drupal 9.0.0.
1113 * Use data with desired wrapper. See https://www.drupal.org/node/2974880.
1115 * @todo Add deprecation warning after it is possible. For more information
1116 * see: https://www.drupal.org/project/drupal/issues/2973400
1118 * @see https://www.drupal.org/node/2940704
1120 Drupal.theme.ajaxWrapperNewContent = ($newContent, ajax, response) =>
1121 (response.effect || ajax.effect) !== 'none' &&
1124 !// We can not consider HTML comments or whitespace text as separate
1125 // roots, since they do not cause visual regression with effect.
1127 $newContent[i].nodeName === '#comment' ||
1128 ($newContent[i].nodeName === '#text' &&
1129 /^(\s|\n|\r)*$/.test($newContent[i].textContent))
1132 ? Drupal.theme('ajaxWrapperMultipleRootElements', $newContent)
1136 * Provide a wrapper for multiple root elements via Ajax.
1138 * @param {jQuery} $elements
1139 * Response elements after parsing.
1141 * @deprecated in Drupal 8.6.x and will be removed before Drupal 9.0.0.
1142 * Use data with desired wrapper. See https://www.drupal.org/node/2974880.
1144 * @todo Add deprecation warning after it is possible. For more information
1145 * see: https://www.drupal.org/project/drupal/issues/2973400
1147 * @see https://www.drupal.org/node/2940704
1149 Drupal.theme.ajaxWrapperMultipleRootElements = $elements =>
1150 $('<div></div>').append($elements);
1153 * @typedef {object} Drupal.AjaxCommands~commandDefinition
1155 * @prop {string} command
1156 * @prop {string} [method]
1157 * @prop {string} [selector]
1158 * @prop {string} [data]
1159 * @prop {object} [settings]
1160 * @prop {bool} [asterisk]
1161 * @prop {string} [text]
1162 * @prop {string} [title]
1163 * @prop {string} [url]
1164 * @prop {object} [argument]
1165 * @prop {string} [name]
1166 * @prop {string} [value]
1167 * @prop {string} [old]
1168 * @prop {string} [new]
1169 * @prop {bool} [merge]
1170 * @prop {Array} [args]
1172 * @see Drupal.AjaxCommands
1176 * Provide a series of commands that the client will perform.
1180 Drupal.AjaxCommands = function() {};
1181 Drupal.AjaxCommands.prototype = {
1183 * Command to insert new content into the DOM.
1185 * @param {Drupal.Ajax} ajax
1186 * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1187 * @param {object} response
1188 * The response from the Ajax request.
1189 * @param {string} response.data
1190 * The data to use with the jQuery method.
1191 * @param {string} [response.method]
1192 * The jQuery DOM manipulation method to be used.
1193 * @param {string} [response.selector]
1194 * A optional jQuery selector string.
1195 * @param {object} [response.settings]
1196 * An optional array of settings that will be used.
1198 insert(ajax, response) {
1199 // Get information from the response. If it is not there, default to
1201 const $wrapper = response.selector
1202 ? $(response.selector)
1204 const method = response.method || ajax.method;
1205 const effect = ajax.getEffect(response);
1207 // Apply any settings from the returned JSON if available.
1208 const settings = response.settings || ajax.settings || drupalSettings;
1210 // Parse response.data into an element collection.
1211 let $newContent = $($.parseHTML(response.data, document, true));
1212 // For backward compatibility, in some cases a wrapper will be added. This
1213 // behavior will be removed before Drupal 9.0.0. If different behavior is
1214 // needed, the theme functions can be overriden.
1215 // @see https://www.drupal.org/node/2940704
1216 $newContent = Drupal.theme(
1217 'ajaxWrapperNewContent',
1223 // If removing content from the wrapper, detach behaviors first.
1230 Drupal.detachBehaviors($wrapper.get(0), settings);
1236 // Add the new content to the page.
1237 $wrapper[method]($newContent);
1239 // Immediately hide the new content if we're using any effects.
1240 if (effect.showEffect !== 'show') {
1244 // Determine which effect to use and what content will receive the
1245 // effect, then show the new content.
1246 const $ajaxNewContent = $newContent.find('.ajax-new-content');
1247 if ($ajaxNewContent.length) {
1248 $ajaxNewContent.hide();
1250 $ajaxNewContent[effect.showEffect](effect.showSpeed);
1251 } else if (effect.showEffect !== 'show') {
1252 $newContent[effect.showEffect](effect.showSpeed);
1255 // Attach all JavaScript behaviors to the new content, if it was
1256 // successfully added to the page, this if statement allows
1257 // `#ajax['wrapper']` to be optional.
1258 if ($newContent.parents('html').length) {
1259 // Attach behaviors to all element nodes.
1260 $newContent.each((index, element) => {
1261 if (element.nodeType === Node.ELEMENT_NODE) {
1262 Drupal.attachBehaviors(element, settings);
1269 * Command to remove a chunk from the page.
1271 * @param {Drupal.Ajax} [ajax]
1272 * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1273 * @param {object} response
1274 * The response from the Ajax request.
1275 * @param {string} response.selector
1276 * A jQuery selector string.
1277 * @param {object} [response.settings]
1278 * An optional array of settings that will be used.
1279 * @param {number} [status]
1280 * The XMLHttpRequest status.
1282 remove(ajax, response, status) {
1283 const settings = response.settings || ajax.settings || drupalSettings;
1284 $(response.selector)
1286 Drupal.detachBehaviors(this, settings);
1292 * Command to mark a chunk changed.
1294 * @param {Drupal.Ajax} [ajax]
1295 * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1296 * @param {object} response
1297 * The JSON response object from the Ajax request.
1298 * @param {string} response.selector
1299 * A jQuery selector string.
1300 * @param {bool} [response.asterisk]
1301 * An optional CSS selector. If specified, an asterisk will be
1302 * appended to the HTML inside the provided selector.
1303 * @param {number} [status]
1304 * The request status.
1306 changed(ajax, response, status) {
1307 const $element = $(response.selector);
1308 if (!$element.hasClass('ajax-changed')) {
1309 $element.addClass('ajax-changed');
1310 if (response.asterisk) {
1312 .find(response.asterisk)
1314 ` <abbr class="ajax-changed" title="${Drupal.t(
1323 * Command to provide an alert.
1325 * @param {Drupal.Ajax} [ajax]
1326 * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1327 * @param {object} response
1328 * The JSON response from the Ajax request.
1329 * @param {string} response.text
1330 * The text that will be displayed in an alert dialog.
1331 * @param {number} [status]
1332 * The XMLHttpRequest status.
1334 alert(ajax, response, status) {
1335 window.alert(response.text, response.title);
1339 * Command to set the window.location, redirecting the browser.
1341 * @param {Drupal.Ajax} [ajax]
1342 * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1343 * @param {object} response
1344 * The response from the Ajax request.
1345 * @param {string} response.url
1346 * The URL to redirect to.
1347 * @param {number} [status]
1348 * The XMLHttpRequest status.
1350 redirect(ajax, response, status) {
1351 window.location = response.url;
1355 * Command to provide the jQuery css() function.
1357 * @param {Drupal.Ajax} [ajax]
1358 * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1359 * @param {object} response
1360 * The response from the Ajax request.
1361 * @param {string} response.selector
1362 * A jQuery selector string.
1363 * @param {object} response.argument
1364 * An array of key/value pairs to set in the CSS for the selector.
1365 * @param {number} [status]
1366 * The XMLHttpRequest status.
1368 css(ajax, response, status) {
1369 $(response.selector).css(response.argument);
1373 * Command to set the settings used for other commands in this response.
1375 * This method will also remove expired `drupalSettings.ajax` settings.
1377 * @param {Drupal.Ajax} [ajax]
1378 * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1379 * @param {object} response
1380 * The response from the Ajax request.
1381 * @param {bool} response.merge
1382 * Determines whether the additional settings should be merged to the
1384 * @param {object} response.settings
1385 * Contains additional settings to add to the global settings.
1386 * @param {number} [status]
1387 * The XMLHttpRequest status.
1389 settings(ajax, response, status) {
1390 const ajaxSettings = drupalSettings.ajax;
1392 // Clean up drupalSettings.ajax.
1394 Drupal.ajax.expired().forEach(instance => {
1395 // If the Ajax object has been created through drupalSettings.ajax
1396 // it will have a selector. When there is no selector the object
1397 // has been initialized with a special class name picked up by the
1400 if (instance.selector) {
1401 const selector = instance.selector.replace('#', '');
1402 if (selector in ajaxSettings) {
1403 delete ajaxSettings[selector];
1409 if (response.merge) {
1410 $.extend(true, drupalSettings, response.settings);
1412 ajax.settings = response.settings;
1417 * Command to attach data using jQuery's data API.
1419 * @param {Drupal.Ajax} [ajax]
1420 * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1421 * @param {object} response
1422 * The response from the Ajax request.
1423 * @param {string} response.name
1424 * The name or key (in the key value pair) of the data attached to this
1426 * @param {string} response.selector
1427 * A jQuery selector string.
1428 * @param {string|object} response.value
1429 * The value of to be attached.
1430 * @param {number} [status]
1431 * The XMLHttpRequest status.
1433 data(ajax, response, status) {
1434 $(response.selector).data(response.name, response.value);
1438 * Command to apply a jQuery method.
1440 * @param {Drupal.Ajax} [ajax]
1441 * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1442 * @param {object} response
1443 * The response from the Ajax request.
1444 * @param {Array} response.args
1445 * An array of arguments to the jQuery method, if any.
1446 * @param {string} response.method
1447 * The jQuery method to invoke.
1448 * @param {string} response.selector
1449 * A jQuery selector string.
1450 * @param {number} [status]
1451 * The XMLHttpRequest status.
1453 invoke(ajax, response, status) {
1454 const $element = $(response.selector);
1455 $element[response.method](...response.args);
1459 * Command to restripe a table.
1461 * @param {Drupal.Ajax} [ajax]
1462 * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1463 * @param {object} response
1464 * The response from the Ajax request.
1465 * @param {string} response.selector
1466 * A jQuery selector string.
1467 * @param {number} [status]
1468 * The XMLHttpRequest status.
1470 restripe(ajax, response, status) {
1471 // :even and :odd are reversed because jQuery counts from 0 and
1472 // we count from 1, so we're out of sync.
1473 // Match immediate children of the parent element to allow nesting.
1474 $(response.selector)
1475 .find('> tbody > tr:visible, > tr:visible')
1476 .removeClass('odd even')
1485 * Command to update a form's build ID.
1487 * @param {Drupal.Ajax} [ajax]
1488 * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1489 * @param {object} response
1490 * The response from the Ajax request.
1491 * @param {string} response.old
1492 * The old form build ID.
1493 * @param {string} response.new
1494 * The new form build ID.
1495 * @param {number} [status]
1496 * The XMLHttpRequest status.
1498 update_build_id(ajax, response, status) {
1499 $(`input[name="form_build_id"][value="${response.old}"]`).val(
1505 * Command to add css.
1507 * Uses the proprietary addImport method if available as browsers which
1508 * support that method ignore @import statements in dynamically added
1511 * @param {Drupal.Ajax} [ajax]
1512 * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
1513 * @param {object} response
1514 * The response from the Ajax request.
1515 * @param {string} response.data
1516 * A string that contains the styles to be added.
1517 * @param {number} [status]
1518 * The XMLHttpRequest status.
1520 add_css(ajax, response, status) {
1521 // Add the styles in the normal way.
1522 $('head').prepend(response.data);
1523 // Add imports in the styles using the addImport method if available.
1525 const importMatch = /^@import url\("(.*)"\);$/gim;
1527 document.styleSheets[0].addImport &&
1528 importMatch.test(response.data)
1530 importMatch.lastIndex = 0;
1532 match = importMatch.exec(response.data);
1533 document.styleSheets[0].addImport(match[1]);
1538 })(jQuery, window, Drupal, drupalSettings);