ajax.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  1. /**
  2. * @file
  3. * Provides Ajax page updating via jQuery $.ajax.
  4. *
  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.
  8. *
  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.
  12. */
  13. (function ($, window, Drupal, drupalSettings) {
  14. 'use strict';
  15. /**
  16. * Attaches the Ajax behavior to each Ajax form element.
  17. *
  18. * @type {Drupal~behavior}
  19. *
  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.
  27. */
  28. Drupal.behaviors.AJAX = {
  29. attach: function (context, settings) {
  30. function loadAjaxBehavior(base) {
  31. var element_settings = settings.ajax[base];
  32. if (typeof element_settings.selector === 'undefined') {
  33. element_settings.selector = '#' + base;
  34. }
  35. $(element_settings.selector).once('drupal-ajax').each(function () {
  36. element_settings.element = this;
  37. element_settings.base = base;
  38. Drupal.ajax(element_settings);
  39. });
  40. }
  41. // Load all Ajax behaviors specified in the settings.
  42. for (var base in settings.ajax) {
  43. if (settings.ajax.hasOwnProperty(base)) {
  44. loadAjaxBehavior(base);
  45. }
  46. }
  47. // Bind Ajax behaviors to all items showing the class.
  48. $('.use-ajax').once('ajax').each(function () {
  49. var element_settings = {};
  50. // Clicked links look better with the throbber than the progress bar.
  51. element_settings.progress = {type: 'throbber'};
  52. // For anchor tags, these will go to the target of the anchor rather
  53. // than the usual location.
  54. var href = $(this).attr('href');
  55. if (href) {
  56. element_settings.url = href;
  57. element_settings.event = 'click';
  58. }
  59. element_settings.dialogType = $(this).data('dialog-type');
  60. element_settings.dialog = $(this).data('dialog-options');
  61. element_settings.base = $(this).attr('id');
  62. element_settings.element = this;
  63. Drupal.ajax(element_settings);
  64. });
  65. // This class means to submit the form to the action using Ajax.
  66. $('.use-ajax-submit').once('ajax').each(function () {
  67. var element_settings = {};
  68. // Ajax submits specified in this manner automatically submit to the
  69. // normal form action.
  70. element_settings.url = $(this.form).attr('action');
  71. // Form submit button clicks need to tell the form what was clicked so
  72. // it gets passed in the POST request.
  73. element_settings.setClick = true;
  74. // Form buttons use the 'click' event rather than mousedown.
  75. element_settings.event = 'click';
  76. // Clicked form buttons look better with the throbber than the progress
  77. // bar.
  78. element_settings.progress = {type: 'throbber'};
  79. element_settings.base = $(this).attr('id');
  80. element_settings.element = this;
  81. Drupal.ajax(element_settings);
  82. });
  83. },
  84. detach: function (context, settings, trigger) {
  85. if (trigger === 'unload') {
  86. Drupal.ajax.expired().forEach(function (instance) {
  87. // Set this to null and allow garbage collection to reclaim
  88. // the memory.
  89. Drupal.ajax.instances[instance.instanceIndex] = null;
  90. });
  91. }
  92. }
  93. };
  94. /**
  95. * Extends Error to provide handling for Errors in Ajax.
  96. *
  97. * @constructor
  98. *
  99. * @augments Error
  100. *
  101. * @param {XMLHttpRequest} xmlhttp
  102. * XMLHttpRequest object used for the failed request.
  103. * @param {string} uri
  104. * The URI where the error occurred.
  105. * @param {string} customMessage
  106. * The custom message.
  107. */
  108. Drupal.AjaxError = function (xmlhttp, uri, customMessage) {
  109. var statusCode;
  110. var statusText;
  111. var pathText;
  112. var responseText;
  113. var readyStateText;
  114. if (xmlhttp.status) {
  115. statusCode = '\n' + Drupal.t('An AJAX HTTP error occurred.') + '\n' + Drupal.t('HTTP Result Code: !status', {'!status': xmlhttp.status});
  116. }
  117. else {
  118. statusCode = '\n' + Drupal.t('An AJAX HTTP request terminated abnormally.');
  119. }
  120. statusCode += '\n' + Drupal.t('Debugging information follows.');
  121. pathText = '\n' + Drupal.t('Path: !uri', {'!uri': uri});
  122. statusText = '';
  123. // In some cases, when statusCode === 0, xmlhttp.statusText may not be
  124. // defined. Unfortunately, testing for it with typeof, etc, doesn't seem to
  125. // catch that and the test causes an exception. So we need to catch the
  126. // exception here.
  127. try {
  128. statusText = '\n' + Drupal.t('StatusText: !statusText', {'!statusText': $.trim(xmlhttp.statusText)});
  129. }
  130. catch (e) {
  131. // Empty.
  132. }
  133. responseText = '';
  134. // Again, we don't have a way to know for sure whether accessing
  135. // xmlhttp.responseText is going to throw an exception. So we'll catch it.
  136. try {
  137. responseText = '\n' + Drupal.t('ResponseText: !responseText', {'!responseText': $.trim(xmlhttp.responseText)});
  138. }
  139. catch (e) {
  140. // Empty.
  141. }
  142. // Make the responseText more readable by stripping HTML tags and newlines.
  143. responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi, '');
  144. responseText = responseText.replace(/[\n]+\s+/g, '\n');
  145. // We don't need readyState except for status == 0.
  146. readyStateText = xmlhttp.status === 0 ? ('\n' + Drupal.t('ReadyState: !readyState', {'!readyState': xmlhttp.readyState})) : '';
  147. customMessage = customMessage ? ('\n' + Drupal.t('CustomMessage: !customMessage', {'!customMessage': customMessage})) : '';
  148. /**
  149. * Formatted and translated error message.
  150. *
  151. * @type {string}
  152. */
  153. this.message = statusCode + pathText + statusText + customMessage + responseText + readyStateText;
  154. /**
  155. * Used by some browsers to display a more accurate stack trace.
  156. *
  157. * @type {string}
  158. */
  159. this.name = 'AjaxError';
  160. };
  161. Drupal.AjaxError.prototype = new Error();
  162. Drupal.AjaxError.prototype.constructor = Drupal.AjaxError;
  163. /**
  164. * Provides Ajax page updating via jQuery $.ajax.
  165. *
  166. * This function is designed to improve developer experience by wrapping the
  167. * initialization of {@link Drupal.Ajax} objects and storing all created
  168. * objects in the {@link Drupal.ajax.instances} array.
  169. *
  170. * @example
  171. * Drupal.behaviors.myCustomAJAXStuff = {
  172. * attach: function (context, settings) {
  173. *
  174. * var ajaxSettings = {
  175. * url: 'my/url/path',
  176. * // If the old version of Drupal.ajax() needs to be used those
  177. * // properties can be added
  178. * base: 'myBase',
  179. * element: $(context).find('.someElement')
  180. * };
  181. *
  182. * var myAjaxObject = Drupal.ajax(ajaxSettings);
  183. *
  184. * // Declare a new Ajax command specifically for this Ajax object.
  185. * myAjaxObject.commands.insert = function (ajax, response, status) {
  186. * $('#my-wrapper').append(response.data);
  187. * alert('New content was appended to #my-wrapper');
  188. * };
  189. *
  190. * // This command will remove this Ajax object from the page.
  191. * myAjaxObject.commands.destroyObject = function (ajax, response, status) {
  192. * Drupal.ajax.instances[this.instanceIndex] = null;
  193. * };
  194. *
  195. * // Programmatically trigger the Ajax request.
  196. * myAjaxObject.execute();
  197. * }
  198. * };
  199. *
  200. * @param {object} settings
  201. * The settings object passed to {@link Drupal.Ajax} constructor.
  202. * @param {string} [settings.base]
  203. * Base is passed to {@link Drupal.Ajax} constructor as the 'base'
  204. * parameter.
  205. * @param {HTMLElement} [settings.element]
  206. * Element parameter of {@link Drupal.Ajax} constructor, element on which
  207. * event listeners will be bound.
  208. *
  209. * @return {Drupal.Ajax}
  210. * The created Ajax object.
  211. *
  212. * @see Drupal.AjaxCommands
  213. */
  214. Drupal.ajax = function (settings) {
  215. if (arguments.length !== 1) {
  216. throw new Error('Drupal.ajax() function must be called with one configuration object only');
  217. }
  218. // Map those config keys to variables for the old Drupal.ajax function.
  219. var base = settings.base || false;
  220. var element = settings.element || false;
  221. delete settings.base;
  222. delete settings.element;
  223. // By default do not display progress for ajax calls without an element.
  224. if (!settings.progress && !element) {
  225. settings.progress = false;
  226. }
  227. var ajax = new Drupal.Ajax(base, element, settings);
  228. ajax.instanceIndex = Drupal.ajax.instances.length;
  229. Drupal.ajax.instances.push(ajax);
  230. return ajax;
  231. };
  232. /**
  233. * Contains all created Ajax objects.
  234. *
  235. * @type {Array.<Drupal.Ajax|null>}
  236. */
  237. Drupal.ajax.instances = [];
  238. /**
  239. * List all objects where the associated element is not in the DOM
  240. *
  241. * This method ignores {@link Drupal.Ajax} objects not bound to DOM elements
  242. * when created with {@link Drupal.ajax}.
  243. *
  244. * @return {Array.<Drupal.Ajax>}
  245. * The list of expired {@link Drupal.Ajax} objects.
  246. */
  247. Drupal.ajax.expired = function () {
  248. return Drupal.ajax.instances.filter(function (instance) {
  249. return instance && instance.element !== false && !document.body.contains(instance.element);
  250. });
  251. };
  252. /**
  253. * Settings for an Ajax object.
  254. *
  255. * @typedef {object} Drupal.Ajax~element_settings
  256. *
  257. * @prop {string} url
  258. * Target of the Ajax request.
  259. * @prop {?string} [event]
  260. * Event bound to settings.element which will trigger the Ajax request.
  261. * @prop {bool} [keypress=true]
  262. * Triggers a request on keypress events.
  263. * @prop {?string} selector
  264. * jQuery selector targeting the element to bind events to or used with
  265. * {@link Drupal.AjaxCommands}.
  266. * @prop {string} [effect='none']
  267. * Name of the jQuery method to use for displaying new Ajax content.
  268. * @prop {string|number} [speed='none']
  269. * Speed with which to apply the effect.
  270. * @prop {string} [method]
  271. * Name of the jQuery method used to insert new content in the targeted
  272. * element.
  273. * @prop {object} [progress]
  274. * Settings for the display of a user-friendly loader.
  275. * @prop {string} [progress.type='throbber']
  276. * Type of progress element, core provides `'bar'`, `'throbber'` and
  277. * `'fullscreen'`.
  278. * @prop {string} [progress.message=Drupal.t('Please wait...')]
  279. * Custom message to be used with the bar indicator.
  280. * @prop {object} [submit]
  281. * Extra data to be sent with the Ajax request.
  282. * @prop {bool} [submit.js=true]
  283. * Allows the PHP side to know this comes from an Ajax request.
  284. * @prop {object} [dialog]
  285. * Options for {@link Drupal.dialog}.
  286. * @prop {string} [dialogType]
  287. * One of `'modal'` or `'dialog'`.
  288. * @prop {string} [prevent]
  289. * List of events on which to stop default action and stop propagation.
  290. */
  291. /**
  292. * Ajax constructor.
  293. *
  294. * The Ajax request returns an array of commands encoded in JSON, which is
  295. * then executed to make any changes that are necessary to the page.
  296. *
  297. * Drupal uses this file to enhance form elements with `#ajax['url']` and
  298. * `#ajax['wrapper']` properties. If set, this file will automatically be
  299. * included to provide Ajax capabilities.
  300. *
  301. * @constructor
  302. *
  303. * @param {string} [base]
  304. * Base parameter of {@link Drupal.Ajax} constructor
  305. * @param {HTMLElement} [element]
  306. * Element parameter of {@link Drupal.Ajax} constructor, element on which
  307. * event listeners will be bound.
  308. * @param {Drupal.Ajax~element_settings} element_settings
  309. * Settings for this Ajax object.
  310. */
  311. Drupal.Ajax = function (base, element, element_settings) {
  312. var defaults = {
  313. event: element ? 'mousedown' : null,
  314. keypress: true,
  315. selector: base ? '#' + base : null,
  316. effect: 'none',
  317. speed: 'none',
  318. method: 'replaceWith',
  319. progress: {
  320. type: 'throbber',
  321. message: Drupal.t('Please wait...')
  322. },
  323. submit: {
  324. js: true
  325. }
  326. };
  327. $.extend(this, defaults, element_settings);
  328. /**
  329. * @type {Drupal.AjaxCommands}
  330. */
  331. this.commands = new Drupal.AjaxCommands();
  332. /**
  333. * @type {bool|number}
  334. */
  335. this.instanceIndex = false;
  336. // @todo Remove this after refactoring the PHP code to:
  337. // - Call this 'selector'.
  338. // - Include the '#' for ID-based selectors.
  339. // - Support non-ID-based selectors.
  340. if (this.wrapper) {
  341. /**
  342. * @type {string}
  343. */
  344. this.wrapper = '#' + this.wrapper;
  345. }
  346. /**
  347. * @type {HTMLElement}
  348. */
  349. this.element = element;
  350. /**
  351. * @type {Drupal.Ajax~element_settings}
  352. */
  353. this.element_settings = element_settings;
  354. // If there isn't a form, jQuery.ajax() will be used instead, allowing us to
  355. // bind Ajax to links as well.
  356. if (this.element && this.element.form) {
  357. /**
  358. * @type {jQuery}
  359. */
  360. this.$form = $(this.element.form);
  361. }
  362. // If no Ajax callback URL was given, use the link href or form action.
  363. if (!this.url) {
  364. var $element = $(this.element);
  365. if ($element.is('a')) {
  366. this.url = $element.attr('href');
  367. }
  368. else if (this.element && element.form) {
  369. this.url = this.$form.attr('action');
  370. }
  371. }
  372. // Replacing 'nojs' with 'ajax' in the URL allows for an easy method to let
  373. // the server detect when it needs to degrade gracefully.
  374. // There are four scenarios to check for:
  375. // 1. /nojs/
  376. // 2. /nojs$ - The end of a URL string.
  377. // 3. /nojs? - Followed by a query (e.g. path/nojs?destination=foobar).
  378. // 4. /nojs# - Followed by a fragment (e.g.: path/nojs#myfragment).
  379. var originalUrl = this.url;
  380. /**
  381. * Processed Ajax URL.
  382. *
  383. * @type {string}
  384. */
  385. this.url = this.url.replace(/\/nojs(\/|$|\?|#)/g, '/ajax$1');
  386. // If the 'nojs' version of the URL is trusted, also trust the 'ajax'
  387. // version.
  388. if (drupalSettings.ajaxTrustedUrl[originalUrl]) {
  389. drupalSettings.ajaxTrustedUrl[this.url] = true;
  390. }
  391. // Set the options for the ajaxSubmit function.
  392. // The 'this' variable will not persist inside of the options object.
  393. var ajax = this;
  394. /**
  395. * Options for the jQuery.ajax function.
  396. *
  397. * @name Drupal.Ajax#options
  398. *
  399. * @type {object}
  400. *
  401. * @prop {string} url
  402. * Ajax URL to be called.
  403. * @prop {object} data
  404. * Ajax payload.
  405. * @prop {function} beforeSerialize
  406. * Implement jQuery beforeSerialize function to call
  407. * {@link Drupal.Ajax#beforeSerialize}.
  408. * @prop {function} beforeSubmit
  409. * Implement jQuery beforeSubmit function to call
  410. * {@link Drupal.Ajax#beforeSubmit}.
  411. * @prop {function} beforeSend
  412. * Implement jQuery beforeSend function to call
  413. * {@link Drupal.Ajax#beforeSend}.
  414. * @prop {function} success
  415. * Implement jQuery success function to call
  416. * {@link Drupal.Ajax#success}.
  417. * @prop {function} complete
  418. * Implement jQuery success function to clean up ajax state and trigger an
  419. * error if needed.
  420. * @prop {string} dataType='json'
  421. * Type of the response expected.
  422. * @prop {string} type='POST'
  423. * HTTP method to use for the Ajax request.
  424. */
  425. ajax.options = {
  426. url: ajax.url,
  427. data: ajax.submit,
  428. beforeSerialize: function (element_settings, options) {
  429. return ajax.beforeSerialize(element_settings, options);
  430. },
  431. beforeSubmit: function (form_values, element_settings, options) {
  432. ajax.ajaxing = true;
  433. return ajax.beforeSubmit(form_values, element_settings, options);
  434. },
  435. beforeSend: function (xmlhttprequest, options) {
  436. ajax.ajaxing = true;
  437. return ajax.beforeSend(xmlhttprequest, options);
  438. },
  439. success: function (response, status, xmlhttprequest) {
  440. // Sanity check for browser support (object expected).
  441. // When using iFrame uploads, responses must be returned as a string.
  442. if (typeof response === 'string') {
  443. response = $.parseJSON(response);
  444. }
  445. // Prior to invoking the response's commands, verify that they can be
  446. // trusted by checking for a response header. See
  447. // \Drupal\Core\EventSubscriber\AjaxResponseSubscriber for details.
  448. // - Empty responses are harmless so can bypass verification. This
  449. // avoids an alert message for server-generated no-op responses that
  450. // skip Ajax rendering.
  451. // - Ajax objects with trusted URLs (e.g., ones defined server-side via
  452. // #ajax) can bypass header verification. This is especially useful
  453. // for Ajax with multipart forms. Because IFRAME transport is used,
  454. // the response headers cannot be accessed for verification.
  455. if (response !== null && !drupalSettings.ajaxTrustedUrl[ajax.url]) {
  456. if (xmlhttprequest.getResponseHeader('X-Drupal-Ajax-Token') !== '1') {
  457. var customMessage = Drupal.t('The response failed verification so will not be processed.');
  458. return ajax.error(xmlhttprequest, ajax.url, customMessage);
  459. }
  460. }
  461. return ajax.success(response, status);
  462. },
  463. complete: function (xmlhttprequest, status) {
  464. ajax.ajaxing = false;
  465. if (status === 'error' || status === 'parsererror') {
  466. return ajax.error(xmlhttprequest, ajax.url);
  467. }
  468. },
  469. dataType: 'json',
  470. type: 'POST'
  471. };
  472. if (element_settings.dialog) {
  473. ajax.options.data.dialogOptions = element_settings.dialog;
  474. }
  475. // Ensure that we have a valid URL by adding ? when no query parameter is
  476. // yet available, otherwise append using &.
  477. if (ajax.options.url.indexOf('?') === -1) {
  478. ajax.options.url += '?';
  479. }
  480. else {
  481. ajax.options.url += '&';
  482. }
  483. ajax.options.url += Drupal.ajax.WRAPPER_FORMAT + '=drupal_' + (element_settings.dialogType || 'ajax');
  484. // Bind the ajaxSubmit function to the element event.
  485. $(ajax.element).on(element_settings.event, function (event) {
  486. if (!drupalSettings.ajaxTrustedUrl[ajax.url] && !Drupal.url.isLocal(ajax.url)) {
  487. throw new Error(Drupal.t('The callback URL is not local and not trusted: !url', {'!url': ajax.url}));
  488. }
  489. return ajax.eventResponse(this, event);
  490. });
  491. // If necessary, enable keyboard submission so that Ajax behaviors
  492. // can be triggered through keyboard input as well as e.g. a mousedown
  493. // action.
  494. if (element_settings.keypress) {
  495. $(ajax.element).on('keypress', function (event) {
  496. return ajax.keypressResponse(this, event);
  497. });
  498. }
  499. // If necessary, prevent the browser default action of an additional event.
  500. // For example, prevent the browser default action of a click, even if the
  501. // Ajax behavior binds to mousedown.
  502. if (element_settings.prevent) {
  503. $(ajax.element).on(element_settings.prevent, false);
  504. }
  505. };
  506. /**
  507. * URL query attribute to indicate the wrapper used to render a request.
  508. *
  509. * The wrapper format determines how the HTML is wrapped, for example in a
  510. * modal dialog.
  511. *
  512. * @const {string}
  513. *
  514. * @default
  515. */
  516. Drupal.ajax.WRAPPER_FORMAT = '_wrapper_format';
  517. /**
  518. * Request parameter to indicate that a request is a Drupal Ajax request.
  519. *
  520. * @const {string}
  521. *
  522. * @default
  523. */
  524. Drupal.Ajax.AJAX_REQUEST_PARAMETER = '_drupal_ajax';
  525. /**
  526. * Execute the ajax request.
  527. *
  528. * Allows developers to execute an Ajax request manually without specifying
  529. * an event to respond to.
  530. *
  531. * @return {object}
  532. * Returns the jQuery.Deferred object underlying the Ajax request. If
  533. * pre-serialization fails, the Deferred will be returned in the rejected
  534. * state.
  535. */
  536. Drupal.Ajax.prototype.execute = function () {
  537. // Do not perform another ajax command if one is already in progress.
  538. if (this.ajaxing) {
  539. return;
  540. }
  541. try {
  542. this.beforeSerialize(this.element, this.options);
  543. // Return the jqXHR so that external code can hook into the Deferred API.
  544. return $.ajax(this.options);
  545. }
  546. catch (e) {
  547. // Unset the ajax.ajaxing flag here because it won't be unset during
  548. // the complete response.
  549. this.ajaxing = false;
  550. window.alert('An error occurred while attempting to process ' + this.options.url + ': ' + e.message);
  551. // For consistency, return a rejected Deferred (i.e., jqXHR's superclass)
  552. // so that calling code can take appropriate action.
  553. return $.Deferred().reject();
  554. }
  555. };
  556. /**
  557. * Handle a key press.
  558. *
  559. * The Ajax object will, if instructed, bind to a key press response. This
  560. * will test to see if the key press is valid to trigger this event and
  561. * if it is, trigger it for us and prevent other keypresses from triggering.
  562. * In this case we're handling RETURN and SPACEBAR keypresses (event codes 13
  563. * and 32. RETURN is often used to submit a form when in a textfield, and
  564. * SPACE is often used to activate an element without submitting.
  565. *
  566. * @param {HTMLElement} element
  567. * Element the event was triggered on.
  568. * @param {jQuery.Event} event
  569. * Triggered event.
  570. */
  571. Drupal.Ajax.prototype.keypressResponse = function (element, event) {
  572. // Create a synonym for this to reduce code confusion.
  573. var ajax = this;
  574. // Detect enter key and space bar and allow the standard response for them,
  575. // except for form elements of type 'text', 'tel', 'number' and 'textarea',
  576. // where the spacebar activation causes inappropriate activation if
  577. // #ajax['keypress'] is TRUE. On a text-type widget a space should always
  578. // be a space.
  579. if (event.which === 13 || (event.which === 32 && element.type !== 'text' &&
  580. element.type !== 'textarea' && element.type !== 'tel' && element.type !== 'number')) {
  581. event.preventDefault();
  582. event.stopPropagation();
  583. $(ajax.element_settings.element).trigger(ajax.element_settings.event);
  584. }
  585. };
  586. /**
  587. * Handle an event that triggers an Ajax response.
  588. *
  589. * When an event that triggers an Ajax response happens, this method will
  590. * perform the actual Ajax call. It is bound to the event using
  591. * bind() in the constructor, and it uses the options specified on the
  592. * Ajax object.
  593. *
  594. * @param {HTMLElement} element
  595. * Element the event was triggered on.
  596. * @param {jQuery.Event} event
  597. * Triggered event.
  598. */
  599. Drupal.Ajax.prototype.eventResponse = function (element, event) {
  600. event.preventDefault();
  601. event.stopPropagation();
  602. // Create a synonym for this to reduce code confusion.
  603. var ajax = this;
  604. // Do not perform another Ajax command if one is already in progress.
  605. if (ajax.ajaxing) {
  606. return;
  607. }
  608. try {
  609. if (ajax.$form) {
  610. // If setClick is set, we must set this to ensure that the button's
  611. // value is passed.
  612. if (ajax.setClick) {
  613. // Mark the clicked button. 'form.clk' is a special variable for
  614. // ajaxSubmit that tells the system which element got clicked to
  615. // trigger the submit. Without it there would be no 'op' or
  616. // equivalent.
  617. element.form.clk = element;
  618. }
  619. ajax.$form.ajaxSubmit(ajax.options);
  620. }
  621. else {
  622. ajax.beforeSerialize(ajax.element, ajax.options);
  623. $.ajax(ajax.options);
  624. }
  625. }
  626. catch (e) {
  627. // Unset the ajax.ajaxing flag here because it won't be unset during
  628. // the complete response.
  629. ajax.ajaxing = false;
  630. window.alert('An error occurred while attempting to process ' + ajax.options.url + ': ' + e.message);
  631. }
  632. };
  633. /**
  634. * Handler for the form serialization.
  635. *
  636. * Runs before the beforeSend() handler (see below), and unlike that one, runs
  637. * before field data is collected.
  638. *
  639. * @param {object} [element]
  640. * Ajax object's `element_settings`.
  641. * @param {object} options
  642. * jQuery.ajax options.
  643. */
  644. Drupal.Ajax.prototype.beforeSerialize = function (element, options) {
  645. // Allow detaching behaviors to update field values before collecting them.
  646. // This is only needed when field values are added to the POST data, so only
  647. // when there is a form such that this.$form.ajaxSubmit() is used instead of
  648. // $.ajax(). When there is no form and $.ajax() is used, beforeSerialize()
  649. // isn't called, but don't rely on that: explicitly check this.$form.
  650. if (this.$form) {
  651. var settings = this.settings || drupalSettings;
  652. Drupal.detachBehaviors(this.$form.get(0), settings, 'serialize');
  653. }
  654. // Inform Drupal that this is an AJAX request.
  655. options.data[Drupal.Ajax.AJAX_REQUEST_PARAMETER] = 1;
  656. // Allow Drupal to return new JavaScript and CSS files to load without
  657. // returning the ones already loaded.
  658. // @see \Drupal\Core\Theme\AjaxBasePageNegotiator
  659. // @see \Drupal\Core\Asset\LibraryDependencyResolverInterface::getMinimalRepresentativeSubset()
  660. // @see system_js_settings_alter()
  661. var pageState = drupalSettings.ajaxPageState;
  662. options.data['ajax_page_state[theme]'] = pageState.theme;
  663. options.data['ajax_page_state[theme_token]'] = pageState.theme_token;
  664. options.data['ajax_page_state[libraries]'] = pageState.libraries;
  665. };
  666. /**
  667. * Modify form values prior to form submission.
  668. *
  669. * @param {Array.<object>} form_values
  670. * Processed form values.
  671. * @param {jQuery} element
  672. * The form node as a jQuery object.
  673. * @param {object} options
  674. * jQuery.ajax options.
  675. */
  676. Drupal.Ajax.prototype.beforeSubmit = function (form_values, element, options) {
  677. // This function is left empty to make it simple to override for modules
  678. // that wish to add functionality here.
  679. };
  680. /**
  681. * Prepare the Ajax request before it is sent.
  682. *
  683. * @param {XMLHttpRequest} xmlhttprequest
  684. * Native Ajax object.
  685. * @param {object} options
  686. * jQuery.ajax options.
  687. */
  688. Drupal.Ajax.prototype.beforeSend = function (xmlhttprequest, options) {
  689. // For forms without file inputs, the jQuery Form plugin serializes the
  690. // form values, and then calls jQuery's $.ajax() function, which invokes
  691. // this handler. In this circumstance, options.extraData is never used. For
  692. // forms with file inputs, the jQuery Form plugin uses the browser's normal
  693. // form submission mechanism, but captures the response in a hidden IFRAME.
  694. // In this circumstance, it calls this handler first, and then appends
  695. // hidden fields to the form to submit the values in options.extraData.
  696. // There is no simple way to know which submission mechanism will be used,
  697. // so we add to extraData regardless, and allow it to be ignored in the
  698. // former case.
  699. if (this.$form) {
  700. options.extraData = options.extraData || {};
  701. // Let the server know when the IFRAME submission mechanism is used. The
  702. // server can use this information to wrap the JSON response in a
  703. // TEXTAREA, as per http://jquery.malsup.com/form/#file-upload.
  704. options.extraData.ajax_iframe_upload = '1';
  705. // The triggering element is about to be disabled (see below), but if it
  706. // contains a value (e.g., a checkbox, textfield, select, etc.), ensure
  707. // that value is included in the submission. As per above, submissions
  708. // that use $.ajax() are already serialized prior to the element being
  709. // disabled, so this is only needed for IFRAME submissions.
  710. var v = $.fieldValue(this.element);
  711. if (v !== null) {
  712. options.extraData[this.element.name] = v;
  713. }
  714. }
  715. // Disable the element that received the change to prevent user interface
  716. // interaction while the Ajax request is in progress. ajax.ajaxing prevents
  717. // the element from triggering a new request, but does not prevent the user
  718. // from changing its value.
  719. $(this.element).prop('disabled', true);
  720. if (!this.progress || !this.progress.type) {
  721. return;
  722. }
  723. // Insert progress indicator.
  724. var progressIndicatorMethod = 'setProgressIndicator' + this.progress.type.slice(0, 1).toUpperCase() + this.progress.type.slice(1).toLowerCase();
  725. if (progressIndicatorMethod in this && typeof this[progressIndicatorMethod] === 'function') {
  726. this[progressIndicatorMethod].call(this);
  727. }
  728. };
  729. /**
  730. * Sets the progress bar progress indicator.
  731. */
  732. Drupal.Ajax.prototype.setProgressIndicatorBar = function () {
  733. var progressBar = new Drupal.ProgressBar('ajax-progress-' + this.element.id, $.noop, this.progress.method, $.noop);
  734. if (this.progress.message) {
  735. progressBar.setProgress(-1, this.progress.message);
  736. }
  737. if (this.progress.url) {
  738. progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500);
  739. }
  740. this.progress.element = $(progressBar.element).addClass('ajax-progress ajax-progress-bar');
  741. this.progress.object = progressBar;
  742. $(this.element).after(this.progress.element);
  743. };
  744. /**
  745. * Sets the throbber progress indicator.
  746. */
  747. Drupal.Ajax.prototype.setProgressIndicatorThrobber = function () {
  748. this.progress.element = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber">&nbsp;</div></div>');
  749. if (this.progress.message) {
  750. this.progress.element.find('.throbber').after('<div class="message">' + this.progress.message + '</div>');
  751. }
  752. $(this.element).after(this.progress.element);
  753. };
  754. /**
  755. * Sets the fullscreen progress indicator.
  756. */
  757. Drupal.Ajax.prototype.setProgressIndicatorFullscreen = function () {
  758. this.progress.element = $('<div class="ajax-progress ajax-progress-fullscreen">&nbsp;</div>');
  759. $('body').after(this.progress.element);
  760. };
  761. /**
  762. * Handler for the form redirection completion.
  763. *
  764. * @param {Array.<Drupal.AjaxCommands~commandDefinition>} response
  765. * Drupal Ajax response.
  766. * @param {number} status
  767. * XMLHttpRequest status.
  768. */
  769. Drupal.Ajax.prototype.success = function (response, status) {
  770. // Remove the progress element.
  771. if (this.progress.element) {
  772. $(this.progress.element).remove();
  773. }
  774. if (this.progress.object) {
  775. this.progress.object.stopMonitoring();
  776. }
  777. $(this.element).prop('disabled', false);
  778. // Save element's ancestors tree so if the element is removed from the dom
  779. // we can try to refocus one of its parents. Using addBack reverse the
  780. // result array, meaning that index 0 is the highest parent in the hierarchy
  781. // in this situation it is usually a <form> element.
  782. var elementParents = $(this.element).parents('[data-drupal-selector]').addBack().toArray();
  783. // Track if any command is altering the focus so we can avoid changing the
  784. // focus set by the Ajax command.
  785. var focusChanged = false;
  786. for (var i in response) {
  787. if (response.hasOwnProperty(i) && response[i].command && this.commands[response[i].command]) {
  788. this.commands[response[i].command](this, response[i], status);
  789. if (response[i].command === 'invoke' && response[i].method === 'focus') {
  790. focusChanged = true;
  791. }
  792. }
  793. }
  794. // If the focus hasn't be changed by the ajax commands, try to refocus the
  795. // triggering element or one of its parents if that element does not exist
  796. // anymore.
  797. if (!focusChanged && this.element && !$(this.element).data('disable-refocus')) {
  798. var target = false;
  799. for (var n = elementParents.length - 1; !target && n > 0; n--) {
  800. target = document.querySelector('[data-drupal-selector="' + elementParents[n].getAttribute('data-drupal-selector') + '"]');
  801. }
  802. if (target) {
  803. $(target).trigger('focus');
  804. }
  805. }
  806. // Reattach behaviors, if they were detached in beforeSerialize(). The
  807. // attachBehaviors() called on the new content from processing the response
  808. // commands is not sufficient, because behaviors from the entire form need
  809. // to be reattached.
  810. if (this.$form) {
  811. var settings = this.settings || drupalSettings;
  812. Drupal.attachBehaviors(this.$form.get(0), settings);
  813. }
  814. // Remove any response-specific settings so they don't get used on the next
  815. // call by mistake.
  816. this.settings = null;
  817. };
  818. /**
  819. * Build an effect object to apply an effect when adding new HTML.
  820. *
  821. * @param {object} response
  822. * Drupal Ajax response.
  823. * @param {string} [response.effect]
  824. * Override the default value of {@link Drupal.Ajax#element_settings}.
  825. * @param {string|number} [response.speed]
  826. * Override the default value of {@link Drupal.Ajax#element_settings}.
  827. *
  828. * @return {object}
  829. * Returns an object with `showEffect`, `hideEffect` and `showSpeed`
  830. * properties.
  831. */
  832. Drupal.Ajax.prototype.getEffect = function (response) {
  833. var type = response.effect || this.effect;
  834. var speed = response.speed || this.speed;
  835. var effect = {};
  836. if (type === 'none') {
  837. effect.showEffect = 'show';
  838. effect.hideEffect = 'hide';
  839. effect.showSpeed = '';
  840. }
  841. else if (type === 'fade') {
  842. effect.showEffect = 'fadeIn';
  843. effect.hideEffect = 'fadeOut';
  844. effect.showSpeed = speed;
  845. }
  846. else {
  847. effect.showEffect = type + 'Toggle';
  848. effect.hideEffect = type + 'Toggle';
  849. effect.showSpeed = speed;
  850. }
  851. return effect;
  852. };
  853. /**
  854. * Handler for the form redirection error.
  855. *
  856. * @param {object} xmlhttprequest
  857. * Native XMLHttpRequest object.
  858. * @param {string} uri
  859. * Ajax Request URI.
  860. * @param {string} [customMessage]
  861. * Extra message to print with the Ajax error.
  862. */
  863. Drupal.Ajax.prototype.error = function (xmlhttprequest, uri, customMessage) {
  864. // Remove the progress element.
  865. if (this.progress.element) {
  866. $(this.progress.element).remove();
  867. }
  868. if (this.progress.object) {
  869. this.progress.object.stopMonitoring();
  870. }
  871. // Undo hide.
  872. $(this.wrapper).show();
  873. // Re-enable the element.
  874. $(this.element).prop('disabled', false);
  875. // Reattach behaviors, if they were detached in beforeSerialize().
  876. if (this.$form) {
  877. var settings = this.settings || drupalSettings;
  878. Drupal.attachBehaviors(this.$form.get(0), settings);
  879. }
  880. throw new Drupal.AjaxError(xmlhttprequest, uri, customMessage);
  881. };
  882. /**
  883. * @typedef {object} Drupal.AjaxCommands~commandDefinition
  884. *
  885. * @prop {string} command
  886. * @prop {string} [method]
  887. * @prop {string} [selector]
  888. * @prop {string} [data]
  889. * @prop {object} [settings]
  890. * @prop {bool} [asterisk]
  891. * @prop {string} [text]
  892. * @prop {string} [title]
  893. * @prop {string} [url]
  894. * @prop {object} [argument]
  895. * @prop {string} [name]
  896. * @prop {string} [value]
  897. * @prop {string} [old]
  898. * @prop {string} [new]
  899. * @prop {bool} [merge]
  900. * @prop {Array} [args]
  901. *
  902. * @see Drupal.AjaxCommands
  903. */
  904. /**
  905. * Provide a series of commands that the client will perform.
  906. *
  907. * @constructor
  908. */
  909. Drupal.AjaxCommands = function () {};
  910. Drupal.AjaxCommands.prototype = {
  911. /**
  912. * Command to insert new content into the DOM.
  913. *
  914. * @param {Drupal.Ajax} ajax
  915. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  916. * @param {object} response
  917. * The response from the Ajax request.
  918. * @param {string} response.data
  919. * The data to use with the jQuery method.
  920. * @param {string} [response.method]
  921. * The jQuery DOM manipulation method to be used.
  922. * @param {string} [response.selector]
  923. * A optional jQuery selector string.
  924. * @param {object} [response.settings]
  925. * An optional array of settings that will be used.
  926. * @param {number} [status]
  927. * The XMLHttpRequest status.
  928. */
  929. insert: function (ajax, response, status) {
  930. // Get information from the response. If it is not there, default to
  931. // our presets.
  932. var $wrapper = response.selector ? $(response.selector) : $(ajax.wrapper);
  933. var method = response.method || ajax.method;
  934. var effect = ajax.getEffect(response);
  935. var settings;
  936. // We don't know what response.data contains: it might be a string of text
  937. // without HTML, so don't rely on jQuery correctly interpreting
  938. // $(response.data) as new HTML rather than a CSS selector. Also, if
  939. // response.data contains top-level text nodes, they get lost with either
  940. // $(response.data) or $('<div></div>').replaceWith(response.data).
  941. var $new_content_wrapped = $('<div></div>').html(response.data);
  942. var $new_content = $new_content_wrapped.contents();
  943. // For legacy reasons, the effects processing code assumes that
  944. // $new_content consists of a single top-level element. Also, it has not
  945. // been sufficiently tested whether attachBehaviors() can be successfully
  946. // called with a context object that includes top-level text nodes.
  947. // However, to give developers full control of the HTML appearing in the
  948. // page, and to enable Ajax content to be inserted in places where <div>
  949. // elements are not allowed (e.g., within <table>, <tr>, and <span>
  950. // parents), we check if the new content satisfies the requirement
  951. // of a single top-level element, and only use the container <div> created
  952. // above when it doesn't. For more information, please see
  953. // https://www.drupal.org/node/736066.
  954. if ($new_content.length !== 1 || $new_content.get(0).nodeType !== 1) {
  955. $new_content = $new_content_wrapped;
  956. }
  957. // If removing content from the wrapper, detach behaviors first.
  958. switch (method) {
  959. case 'html':
  960. case 'replaceWith':
  961. case 'replaceAll':
  962. case 'empty':
  963. case 'remove':
  964. settings = response.settings || ajax.settings || drupalSettings;
  965. Drupal.detachBehaviors($wrapper.get(0), settings);
  966. }
  967. // Add the new content to the page.
  968. $wrapper[method]($new_content);
  969. // Immediately hide the new content if we're using any effects.
  970. if (effect.showEffect !== 'show') {
  971. $new_content.hide();
  972. }
  973. // Determine which effect to use and what content will receive the
  974. // effect, then show the new content.
  975. if ($new_content.find('.ajax-new-content').length > 0) {
  976. $new_content.find('.ajax-new-content').hide();
  977. $new_content.show();
  978. $new_content.find('.ajax-new-content')[effect.showEffect](effect.showSpeed);
  979. }
  980. else if (effect.showEffect !== 'show') {
  981. $new_content[effect.showEffect](effect.showSpeed);
  982. }
  983. // Attach all JavaScript behaviors to the new content, if it was
  984. // successfully added to the page, this if statement allows
  985. // `#ajax['wrapper']` to be optional.
  986. if ($new_content.parents('html').length > 0) {
  987. // Apply any settings from the returned JSON if available.
  988. settings = response.settings || ajax.settings || drupalSettings;
  989. Drupal.attachBehaviors($new_content.get(0), settings);
  990. }
  991. },
  992. /**
  993. * Command to remove a chunk from the page.
  994. *
  995. * @param {Drupal.Ajax} [ajax]
  996. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  997. * @param {object} response
  998. * The response from the Ajax request.
  999. * @param {string} response.selector
  1000. * A jQuery selector string.
  1001. * @param {object} [response.settings]
  1002. * An optional array of settings that will be used.
  1003. * @param {number} [status]
  1004. * The XMLHttpRequest status.
  1005. */
  1006. remove: function (ajax, response, status) {
  1007. var settings = response.settings || ajax.settings || drupalSettings;
  1008. $(response.selector).each(function () {
  1009. Drupal.detachBehaviors(this, settings);
  1010. })
  1011. .remove();
  1012. },
  1013. /**
  1014. * Command to mark a chunk changed.
  1015. *
  1016. * @param {Drupal.Ajax} [ajax]
  1017. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1018. * @param {object} response
  1019. * The JSON response object from the Ajax request.
  1020. * @param {string} response.selector
  1021. * A jQuery selector string.
  1022. * @param {bool} [response.asterisk]
  1023. * An optional CSS selector. If specified, an asterisk will be
  1024. * appended to the HTML inside the provided selector.
  1025. * @param {number} [status]
  1026. * The request status.
  1027. */
  1028. changed: function (ajax, response, status) {
  1029. var $element = $(response.selector);
  1030. if (!$element.hasClass('ajax-changed')) {
  1031. $element.addClass('ajax-changed');
  1032. if (response.asterisk) {
  1033. $element.find(response.asterisk).append(' <abbr class="ajax-changed" title="' + Drupal.t('Changed') + '">*</abbr> ');
  1034. }
  1035. }
  1036. },
  1037. /**
  1038. * Command to provide an alert.
  1039. *
  1040. * @param {Drupal.Ajax} [ajax]
  1041. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1042. * @param {object} response
  1043. * The JSON response from the Ajax request.
  1044. * @param {string} response.text
  1045. * The text that will be displayed in an alert dialog.
  1046. * @param {number} [status]
  1047. * The XMLHttpRequest status.
  1048. */
  1049. alert: function (ajax, response, status) {
  1050. window.alert(response.text, response.title);
  1051. },
  1052. /**
  1053. * Command to set the window.location, redirecting the browser.
  1054. *
  1055. * @param {Drupal.Ajax} [ajax]
  1056. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1057. * @param {object} response
  1058. * The response from the Ajax request.
  1059. * @param {string} response.url
  1060. * The URL to redirect to.
  1061. * @param {number} [status]
  1062. * The XMLHttpRequest status.
  1063. */
  1064. redirect: function (ajax, response, status) {
  1065. window.location = response.url;
  1066. },
  1067. /**
  1068. * Command to provide the jQuery css() function.
  1069. *
  1070. * @param {Drupal.Ajax} [ajax]
  1071. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1072. * @param {object} response
  1073. * The response from the Ajax request.
  1074. * @param {string} response.selector
  1075. * A jQuery selector string.
  1076. * @param {object} response.argument
  1077. * An array of key/value pairs to set in the CSS for the selector.
  1078. * @param {number} [status]
  1079. * The XMLHttpRequest status.
  1080. */
  1081. css: function (ajax, response, status) {
  1082. $(response.selector).css(response.argument);
  1083. },
  1084. /**
  1085. * Command to set the settings used for other commands in this response.
  1086. *
  1087. * This method will also remove expired `drupalSettings.ajax` settings.
  1088. *
  1089. * @param {Drupal.Ajax} [ajax]
  1090. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1091. * @param {object} response
  1092. * The response from the Ajax request.
  1093. * @param {bool} response.merge
  1094. * Determines whether the additional settings should be merged to the
  1095. * global settings.
  1096. * @param {object} response.settings
  1097. * Contains additional settings to add to the global settings.
  1098. * @param {number} [status]
  1099. * The XMLHttpRequest status.
  1100. */
  1101. settings: function (ajax, response, status) {
  1102. var ajaxSettings = drupalSettings.ajax;
  1103. // Clean up drupalSettings.ajax.
  1104. if (ajaxSettings) {
  1105. Drupal.ajax.expired().forEach(function (instance) {
  1106. // If the Ajax object has been created through drupalSettings.ajax
  1107. // it will have a selector. When there is no selector the object
  1108. // has been initialized with a special class name picked up by the
  1109. // Ajax behavior.
  1110. if (instance.selector) {
  1111. var selector = instance.selector.replace('#', '');
  1112. if (selector in ajaxSettings) {
  1113. delete ajaxSettings[selector];
  1114. }
  1115. }
  1116. });
  1117. }
  1118. if (response.merge) {
  1119. $.extend(true, drupalSettings, response.settings);
  1120. }
  1121. else {
  1122. ajax.settings = response.settings;
  1123. }
  1124. },
  1125. /**
  1126. * Command to attach data using jQuery's data API.
  1127. *
  1128. * @param {Drupal.Ajax} [ajax]
  1129. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1130. * @param {object} response
  1131. * The response from the Ajax request.
  1132. * @param {string} response.name
  1133. * The name or key (in the key value pair) of the data attached to this
  1134. * selector.
  1135. * @param {string} response.selector
  1136. * A jQuery selector string.
  1137. * @param {string|object} response.value
  1138. * The value of to be attached.
  1139. * @param {number} [status]
  1140. * The XMLHttpRequest status.
  1141. */
  1142. data: function (ajax, response, status) {
  1143. $(response.selector).data(response.name, response.value);
  1144. },
  1145. /**
  1146. * Command to apply a jQuery method.
  1147. *
  1148. * @param {Drupal.Ajax} [ajax]
  1149. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1150. * @param {object} response
  1151. * The response from the Ajax request.
  1152. * @param {Array} response.args
  1153. * An array of arguments to the jQuery method, if any.
  1154. * @param {string} response.method
  1155. * The jQuery method to invoke.
  1156. * @param {string} response.selector
  1157. * A jQuery selector string.
  1158. * @param {number} [status]
  1159. * The XMLHttpRequest status.
  1160. */
  1161. invoke: function (ajax, response, status) {
  1162. var $element = $(response.selector);
  1163. $element[response.method].apply($element, response.args);
  1164. },
  1165. /**
  1166. * Command to restripe a table.
  1167. *
  1168. * @param {Drupal.Ajax} [ajax]
  1169. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1170. * @param {object} response
  1171. * The response from the Ajax request.
  1172. * @param {string} response.selector
  1173. * A jQuery selector string.
  1174. * @param {number} [status]
  1175. * The XMLHttpRequest status.
  1176. */
  1177. restripe: function (ajax, response, status) {
  1178. // :even and :odd are reversed because jQuery counts from 0 and
  1179. // we count from 1, so we're out of sync.
  1180. // Match immediate children of the parent element to allow nesting.
  1181. $(response.selector).find('> tbody > tr:visible, > tr:visible')
  1182. .removeClass('odd even')
  1183. .filter(':even').addClass('odd').end()
  1184. .filter(':odd').addClass('even');
  1185. },
  1186. /**
  1187. * Command to update a form's build ID.
  1188. *
  1189. * @param {Drupal.Ajax} [ajax]
  1190. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1191. * @param {object} response
  1192. * The response from the Ajax request.
  1193. * @param {string} response.old
  1194. * The old form build ID.
  1195. * @param {string} response.new
  1196. * The new form build ID.
  1197. * @param {number} [status]
  1198. * The XMLHttpRequest status.
  1199. */
  1200. update_build_id: function (ajax, response, status) {
  1201. $('input[name="form_build_id"][value="' + response.old + '"]').val(response.new);
  1202. },
  1203. /**
  1204. * Command to add css.
  1205. *
  1206. * Uses the proprietary addImport method if available as browsers which
  1207. * support that method ignore @import statements in dynamically added
  1208. * stylesheets.
  1209. *
  1210. * @param {Drupal.Ajax} [ajax]
  1211. * {@link Drupal.Ajax} object created by {@link Drupal.ajax}.
  1212. * @param {object} response
  1213. * The response from the Ajax request.
  1214. * @param {string} response.data
  1215. * A string that contains the styles to be added.
  1216. * @param {number} [status]
  1217. * The XMLHttpRequest status.
  1218. */
  1219. add_css: function (ajax, response, status) {
  1220. // Add the styles in the normal way.
  1221. $('head').prepend(response.data);
  1222. // Add imports in the styles using the addImport method if available.
  1223. var match;
  1224. var importMatch = /^@import url\("(.*)"\);$/igm;
  1225. if (document.styleSheets[0].addImport && importMatch.test(response.data)) {
  1226. importMatch.lastIndex = 0;
  1227. do {
  1228. match = importMatch.exec(response.data);
  1229. document.styleSheets[0].addImport(match[1]);
  1230. } while (match);
  1231. }
  1232. }
  1233. };
  1234. })(jQuery, window, Drupal, drupalSettings);