ajax.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. (function ($) {
  2. /**
  3. * Provides Ajax page updating via jQuery $.ajax (Asynchronous JavaScript and XML).
  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['path'] and
  10. * #ajax['wrapper'] properties. If set, this file will automatically be included
  11. * to provide Ajax capabilities.
  12. */
  13. Drupal.ajax = Drupal.ajax || {};
  14. Drupal.settings.urlIsAjaxTrusted = Drupal.settings.urlIsAjaxTrusted || {};
  15. /**
  16. * Attaches the Ajax behavior to each Ajax form element.
  17. */
  18. Drupal.behaviors.AJAX = {
  19. attach: function (context, settings) {
  20. // Load all Ajax behaviors specified in the settings.
  21. for (var base in settings.ajax) {
  22. if (!$('#' + base + '.ajax-processed').length) {
  23. var element_settings = settings.ajax[base];
  24. if (typeof element_settings.selector == 'undefined') {
  25. element_settings.selector = '#' + base;
  26. }
  27. $(element_settings.selector).each(function () {
  28. element_settings.element = this;
  29. Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
  30. });
  31. $('#' + base).addClass('ajax-processed');
  32. }
  33. }
  34. // Bind Ajax behaviors to all items showing the class.
  35. $('.use-ajax:not(.ajax-processed)').addClass('ajax-processed').each(function () {
  36. var element_settings = {};
  37. // Clicked links look better with the throbber than the progress bar.
  38. element_settings.progress = { 'type': 'throbber' };
  39. // For anchor tags, these will go to the target of the anchor rather
  40. // than the usual location.
  41. if ($(this).attr('href')) {
  42. element_settings.url = $(this).attr('href');
  43. element_settings.event = 'click';
  44. }
  45. var base = $(this).attr('id');
  46. Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
  47. });
  48. // This class means to submit the form to the action using Ajax.
  49. $('.use-ajax-submit:not(.ajax-processed)').addClass('ajax-processed').each(function () {
  50. var element_settings = {};
  51. // Ajax submits specified in this manner automatically submit to the
  52. // normal form action.
  53. element_settings.url = $(this.form).attr('action');
  54. // Form submit button clicks need to tell the form what was clicked so
  55. // it gets passed in the POST request.
  56. element_settings.setClick = true;
  57. // Form buttons use the 'click' event rather than mousedown.
  58. element_settings.event = 'click';
  59. // Clicked form buttons look better with the throbber than the progress bar.
  60. element_settings.progress = { 'type': 'throbber' };
  61. var base = $(this).attr('id');
  62. Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
  63. });
  64. }
  65. };
  66. /**
  67. * Ajax object.
  68. *
  69. * All Ajax objects on a page are accessible through the global Drupal.ajax
  70. * object and are keyed by the submit button's ID. You can access them from
  71. * your module's JavaScript file to override properties or functions.
  72. *
  73. * For example, if your Ajax enabled button has the ID 'edit-submit', you can
  74. * redefine the function that is called to insert the new content like this
  75. * (inside a Drupal.behaviors attach block):
  76. * @code
  77. * Drupal.behaviors.myCustomAJAXStuff = {
  78. * attach: function (context, settings) {
  79. * Drupal.ajax['edit-submit'].commands.insert = function (ajax, response, status) {
  80. * new_content = $(response.data);
  81. * $('#my-wrapper').append(new_content);
  82. * alert('New content was appended to #my-wrapper');
  83. * }
  84. * }
  85. * };
  86. * @endcode
  87. */
  88. Drupal.ajax = function (base, element, element_settings) {
  89. var defaults = {
  90. url: 'system/ajax',
  91. event: 'mousedown',
  92. keypress: true,
  93. selector: '#' + base,
  94. effect: 'none',
  95. speed: 'none',
  96. method: 'replaceWith',
  97. progress: {
  98. type: 'throbber',
  99. message: Drupal.t('Please wait...')
  100. },
  101. submit: {
  102. 'js': true
  103. }
  104. };
  105. $.extend(this, defaults, element_settings);
  106. this.element = element;
  107. this.element_settings = element_settings;
  108. // Replacing 'nojs' with 'ajax' in the URL allows for an easy method to let
  109. // the server detect when it needs to degrade gracefully.
  110. // There are five scenarios to check for:
  111. // 1. /nojs/
  112. // 2. /nojs$ - The end of a URL string.
  113. // 3. /nojs? - Followed by a query (with clean URLs enabled).
  114. // E.g.: path/nojs?destination=foobar
  115. // 4. /nojs& - Followed by a query (without clean URLs enabled).
  116. // E.g.: ?q=path/nojs&destination=foobar
  117. // 5. /nojs# - Followed by a fragment.
  118. // E.g.: path/nojs#myfragment
  119. this.url = element_settings.url.replace(/\/nojs(\/|$|\?|&|#)/g, '/ajax$1');
  120. // If the 'nojs' version of the URL is trusted, also trust the 'ajax' version.
  121. if (Drupal.settings.urlIsAjaxTrusted[element_settings.url]) {
  122. Drupal.settings.urlIsAjaxTrusted[this.url] = true;
  123. }
  124. this.wrapper = '#' + element_settings.wrapper;
  125. // If there isn't a form, jQuery.ajax() will be used instead, allowing us to
  126. // bind Ajax to links as well.
  127. if (this.element.form) {
  128. this.form = $(this.element.form);
  129. }
  130. // Set the options for the ajaxSubmit function.
  131. // The 'this' variable will not persist inside of the options object.
  132. var ajax = this;
  133. ajax.options = {
  134. url: Drupal.sanitizeAjaxUrl(ajax.url),
  135. data: ajax.submit,
  136. beforeSerialize: function (element_settings, options) {
  137. return ajax.beforeSerialize(element_settings, options);
  138. },
  139. beforeSubmit: function (form_values, element_settings, options) {
  140. ajax.ajaxing = true;
  141. return ajax.beforeSubmit(form_values, element_settings, options);
  142. },
  143. beforeSend: function (xmlhttprequest, options) {
  144. ajax.ajaxing = true;
  145. return ajax.beforeSend(xmlhttprequest, options);
  146. },
  147. success: function (response, status, xmlhttprequest) {
  148. // Sanity check for browser support (object expected).
  149. // When using iFrame uploads, responses must be returned as a string.
  150. if (typeof response == 'string') {
  151. response = $.parseJSON(response);
  152. }
  153. // Prior to invoking the response's commands, verify that they can be
  154. // trusted by checking for a response header. See
  155. // ajax_set_verification_header() for details.
  156. // - Empty responses are harmless so can bypass verification. This avoids
  157. // an alert message for server-generated no-op responses that skip Ajax
  158. // rendering.
  159. // - Ajax objects with trusted URLs (e.g., ones defined server-side via
  160. // #ajax) can bypass header verification. This is especially useful for
  161. // Ajax with multipart forms. Because IFRAME transport is used, the
  162. // response headers cannot be accessed for verification.
  163. if (response !== null && !Drupal.settings.urlIsAjaxTrusted[ajax.url]) {
  164. if (xmlhttprequest.getResponseHeader('X-Drupal-Ajax-Token') !== '1') {
  165. var customMessage = Drupal.t("The response failed verification so will not be processed.");
  166. return ajax.error(xmlhttprequest, ajax.url, customMessage);
  167. }
  168. }
  169. return ajax.success(response, status);
  170. },
  171. complete: function (xmlhttprequest, status) {
  172. ajax.ajaxing = false;
  173. if (status == 'error' || status == 'parsererror') {
  174. return ajax.error(xmlhttprequest, ajax.url);
  175. }
  176. },
  177. dataType: 'json',
  178. jsonp: false,
  179. type: 'POST'
  180. };
  181. // For multipart forms (e.g., file uploads), jQuery Form targets the form
  182. // submission to an iframe instead of using an XHR object. The initial "src"
  183. // of the iframe, prior to the form submission, is set to options.iframeSrc.
  184. // "about:blank" is the semantically correct, standards-compliant, way to
  185. // initialize a blank iframe; however, some old IE versions (possibly only 6)
  186. // incorrectly report a mixed content warning when iframes with an
  187. // "about:blank" src are added to a parent document with an https:// origin.
  188. // jQuery Form works around this by defaulting to "javascript:false" instead,
  189. // but that breaks on Chrome 83, so here we force the semantically correct
  190. // behavior for all browsers except old IE.
  191. // @see https://www.drupal.org/project/drupal/issues/3143016
  192. // @see https://github.com/jquery-form/form/blob/df9cb101b9c9c085c8d75ad980c7ff1cf62063a1/jquery.form.js#L68
  193. // @see https://bugs.chromium.org/p/chromium/issues/detail?id=1084874
  194. // @see https://html.spec.whatwg.org/multipage/browsers.html#creating-browsing-contexts
  195. // @see https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
  196. if (navigator.userAgent.indexOf("MSIE") === -1) {
  197. ajax.options.iframeSrc = 'about:blank';
  198. }
  199. // Bind the ajaxSubmit function to the element event.
  200. $(ajax.element).bind(element_settings.event, function (event) {
  201. if (!Drupal.settings.urlIsAjaxTrusted[ajax.url] && !Drupal.urlIsLocal(ajax.url)) {
  202. throw new Error(Drupal.t('The callback URL is not local and not trusted: !url', {'!url': ajax.url}));
  203. }
  204. return ajax.eventResponse(this, event);
  205. });
  206. // If necessary, enable keyboard submission so that Ajax behaviors
  207. // can be triggered through keyboard input as well as e.g. a mousedown
  208. // action.
  209. if (element_settings.keypress) {
  210. $(ajax.element).keypress(function (event) {
  211. return ajax.keypressResponse(this, event);
  212. });
  213. }
  214. // If necessary, prevent the browser default action of an additional event.
  215. // For example, prevent the browser default action of a click, even if the
  216. // AJAX behavior binds to mousedown.
  217. if (element_settings.prevent) {
  218. $(ajax.element).bind(element_settings.prevent, false);
  219. }
  220. };
  221. /**
  222. * Handle a key press.
  223. *
  224. * The Ajax object will, if instructed, bind to a key press response. This
  225. * will test to see if the key press is valid to trigger this event and
  226. * if it is, trigger it for us and prevent other keypresses from triggering.
  227. * In this case we're handling RETURN and SPACEBAR keypresses (event codes 13
  228. * and 32. RETURN is often used to submit a form when in a textfield, and
  229. * SPACE is often used to activate an element without submitting.
  230. */
  231. Drupal.ajax.prototype.keypressResponse = function (element, event) {
  232. // Create a synonym for this to reduce code confusion.
  233. var ajax = this;
  234. // Detect enter key and space bar and allow the standard response for them,
  235. // except for form elements of type 'text' and 'textarea', where the
  236. // spacebar activation causes inappropriate activation if #ajax['keypress'] is
  237. // TRUE. On a text-type widget a space should always be a space.
  238. if (event.which == 13 || (event.which == 32 && element.type != 'text' && element.type != 'textarea')) {
  239. $(ajax.element_settings.element).trigger(ajax.element_settings.event);
  240. return false;
  241. }
  242. };
  243. /**
  244. * Handle an event that triggers an Ajax response.
  245. *
  246. * When an event that triggers an Ajax response happens, this method will
  247. * perform the actual Ajax call. It is bound to the event using
  248. * bind() in the constructor, and it uses the options specified on the
  249. * ajax object.
  250. */
  251. Drupal.ajax.prototype.eventResponse = function (element, event) {
  252. // Create a synonym for this to reduce code confusion.
  253. var ajax = this;
  254. // Do not perform another ajax command if one is already in progress.
  255. if (ajax.ajaxing) {
  256. return false;
  257. }
  258. try {
  259. if (ajax.form) {
  260. // If setClick is set, we must set this to ensure that the button's
  261. // value is passed.
  262. if (ajax.setClick) {
  263. // Mark the clicked button. 'form.clk' is a special variable for
  264. // ajaxSubmit that tells the system which element got clicked to
  265. // trigger the submit. Without it there would be no 'op' or
  266. // equivalent.
  267. element.form.clk = element;
  268. }
  269. ajax.form.ajaxSubmit(ajax.options);
  270. }
  271. else {
  272. ajax.beforeSerialize(ajax.element, ajax.options);
  273. $.ajax(ajax.options);
  274. }
  275. }
  276. catch (e) {
  277. // Unset the ajax.ajaxing flag here because it won't be unset during
  278. // the complete response.
  279. ajax.ajaxing = false;
  280. alert("An error occurred while attempting to process " + ajax.options.url + ": " + e.message);
  281. }
  282. // For radio/checkbox, allow the default event. On IE, this means letting
  283. // it actually check the box.
  284. if (typeof element.type != 'undefined' && (element.type == 'checkbox' || element.type == 'radio')) {
  285. return true;
  286. }
  287. else {
  288. return false;
  289. }
  290. };
  291. /**
  292. * Handler for the form serialization.
  293. *
  294. * Runs before the beforeSend() handler (see below), and unlike that one, runs
  295. * before field data is collected.
  296. */
  297. Drupal.ajax.prototype.beforeSerialize = function (element, options) {
  298. // Allow detaching behaviors to update field values before collecting them.
  299. // This is only needed when field values are added to the POST data, so only
  300. // when there is a form such that this.form.ajaxSubmit() is used instead of
  301. // $.ajax(). When there is no form and $.ajax() is used, beforeSerialize()
  302. // isn't called, but don't rely on that: explicitly check this.form.
  303. if (this.form) {
  304. var settings = this.settings || Drupal.settings;
  305. Drupal.detachBehaviors(this.form, settings, 'serialize');
  306. }
  307. // Prevent duplicate HTML ids in the returned markup.
  308. // @see drupal_html_id()
  309. options.data['ajax_html_ids[]'] = [];
  310. $('[id]').each(function () {
  311. options.data['ajax_html_ids[]'].push(this.id);
  312. });
  313. // Allow Drupal to return new JavaScript and CSS files to load without
  314. // returning the ones already loaded.
  315. // @see ajax_base_page_theme()
  316. // @see drupal_get_css()
  317. // @see drupal_get_js()
  318. options.data['ajax_page_state[theme]'] = Drupal.settings.ajaxPageState.theme;
  319. options.data['ajax_page_state[theme_token]'] = Drupal.settings.ajaxPageState.theme_token;
  320. for (var key in Drupal.settings.ajaxPageState.css) {
  321. options.data['ajax_page_state[css][' + key + ']'] = 1;
  322. }
  323. for (var key in Drupal.settings.ajaxPageState.js) {
  324. options.data['ajax_page_state[js][' + key + ']'] = 1;
  325. }
  326. };
  327. /**
  328. * Modify form values prior to form submission.
  329. */
  330. Drupal.ajax.prototype.beforeSubmit = function (form_values, element, options) {
  331. // This function is left empty to make it simple to override for modules
  332. // that wish to add functionality here.
  333. };
  334. /**
  335. * Prepare the Ajax request before it is sent.
  336. */
  337. Drupal.ajax.prototype.beforeSend = function (xmlhttprequest, options) {
  338. // For forms without file inputs, the jQuery Form plugin serializes the form
  339. // values, and then calls jQuery's $.ajax() function, which invokes this
  340. // handler. In this circumstance, options.extraData is never used. For forms
  341. // with file inputs, the jQuery Form plugin uses the browser's normal form
  342. // submission mechanism, but captures the response in a hidden IFRAME. In this
  343. // circumstance, it calls this handler first, and then appends hidden fields
  344. // to the form to submit the values in options.extraData. There is no simple
  345. // way to know which submission mechanism will be used, so we add to extraData
  346. // regardless, and allow it to be ignored in the former case.
  347. if (this.form) {
  348. options.extraData = options.extraData || {};
  349. // Let the server know when the IFRAME submission mechanism is used. The
  350. // server can use this information to wrap the JSON response in a TEXTAREA,
  351. // as per http://jquery.malsup.com/form/#file-upload.
  352. options.extraData.ajax_iframe_upload = '1';
  353. // The triggering element is about to be disabled (see below), but if it
  354. // contains a value (e.g., a checkbox, textfield, select, etc.), ensure that
  355. // value is included in the submission. As per above, submissions that use
  356. // $.ajax() are already serialized prior to the element being disabled, so
  357. // this is only needed for IFRAME submissions.
  358. var v = $.fieldValue(this.element);
  359. if (v !== null) {
  360. options.extraData[this.element.name] = Drupal.checkPlain(v);
  361. }
  362. }
  363. // Disable the element that received the change to prevent user interface
  364. // interaction while the Ajax request is in progress. ajax.ajaxing prevents
  365. // the element from triggering a new request, but does not prevent the user
  366. // from changing its value.
  367. $(this.element).addClass('progress-disabled').attr('disabled', true);
  368. // Insert progressbar or throbber.
  369. if (this.progress.type == 'bar') {
  370. var progressBar = new Drupal.progressBar('ajax-progress-' + this.element.id, $.noop, this.progress.method, $.noop);
  371. if (this.progress.message) {
  372. progressBar.setProgress(-1, this.progress.message);
  373. }
  374. if (this.progress.url) {
  375. progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500);
  376. }
  377. this.progress.element = $(progressBar.element).addClass('ajax-progress ajax-progress-bar');
  378. this.progress.object = progressBar;
  379. $(this.element).after(this.progress.element);
  380. }
  381. else if (this.progress.type == 'throbber') {
  382. this.progress.element = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber">&nbsp;</div></div>');
  383. if (this.progress.message) {
  384. $('.throbber', this.progress.element).after('<div class="message">' + this.progress.message + '</div>');
  385. }
  386. $(this.element).after(this.progress.element);
  387. }
  388. };
  389. /**
  390. * Handler for the form redirection completion.
  391. */
  392. Drupal.ajax.prototype.success = function (response, status) {
  393. // Remove the progress element.
  394. if (this.progress.element) {
  395. $(this.progress.element).remove();
  396. }
  397. if (this.progress.object) {
  398. this.progress.object.stopMonitoring();
  399. }
  400. $(this.element).removeClass('progress-disabled').removeAttr('disabled');
  401. Drupal.freezeHeight();
  402. for (var i in response) {
  403. if (response.hasOwnProperty(i) && response[i]['command'] && this.commands[response[i]['command']]) {
  404. this.commands[response[i]['command']](this, response[i], status);
  405. }
  406. }
  407. // Reattach behaviors, if they were detached in beforeSerialize(). The
  408. // attachBehaviors() called on the new content from processing the response
  409. // commands is not sufficient, because behaviors from the entire form need
  410. // to be reattached.
  411. if (this.form) {
  412. var settings = this.settings || Drupal.settings;
  413. Drupal.attachBehaviors(this.form, settings);
  414. }
  415. Drupal.unfreezeHeight();
  416. // Remove any response-specific settings so they don't get used on the next
  417. // call by mistake.
  418. this.settings = null;
  419. };
  420. /**
  421. * Build an effect object which tells us how to apply the effect when adding new HTML.
  422. */
  423. Drupal.ajax.prototype.getEffect = function (response) {
  424. var type = response.effect || this.effect;
  425. var speed = response.speed || this.speed;
  426. var effect = {};
  427. if (type == 'none') {
  428. effect.showEffect = 'show';
  429. effect.hideEffect = 'hide';
  430. effect.showSpeed = '';
  431. }
  432. else if (type == 'fade') {
  433. effect.showEffect = 'fadeIn';
  434. effect.hideEffect = 'fadeOut';
  435. effect.showSpeed = speed;
  436. }
  437. else {
  438. effect.showEffect = type + 'Toggle';
  439. effect.hideEffect = type + 'Toggle';
  440. effect.showSpeed = speed;
  441. }
  442. return effect;
  443. };
  444. /**
  445. * Handler for the form redirection error.
  446. */
  447. Drupal.ajax.prototype.error = function (xmlhttprequest, uri, customMessage) {
  448. Drupal.displayAjaxError(Drupal.ajaxError(xmlhttprequest, uri, customMessage));
  449. // Remove the progress element.
  450. if (this.progress.element) {
  451. $(this.progress.element).remove();
  452. }
  453. if (this.progress.object) {
  454. this.progress.object.stopMonitoring();
  455. }
  456. // Undo hide.
  457. $(this.wrapper).show();
  458. // Re-enable the element.
  459. $(this.element).removeClass('progress-disabled').removeAttr('disabled');
  460. // Reattach behaviors, if they were detached in beforeSerialize().
  461. if (this.form) {
  462. var settings = this.settings || Drupal.settings;
  463. Drupal.attachBehaviors(this.form, settings);
  464. }
  465. };
  466. /**
  467. * Provide a series of commands that the server can request the client perform.
  468. */
  469. Drupal.ajax.prototype.commands = {
  470. /**
  471. * Command to insert new content into the DOM.
  472. */
  473. insert: function (ajax, response, status) {
  474. // Get information from the response. If it is not there, default to
  475. // our presets.
  476. var wrapper = response.selector ? $(response.selector) : $(ajax.wrapper);
  477. var method = response.method || ajax.method;
  478. var effect = ajax.getEffect(response);
  479. // We don't know what response.data contains: it might be a string of text
  480. // without HTML, so don't rely on jQuery correctly iterpreting
  481. // $(response.data) as new HTML rather than a CSS selector. Also, if
  482. // response.data contains top-level text nodes, they get lost with either
  483. // $(response.data) or $('<div></div>').replaceWith(response.data).
  484. var new_content_wrapped = $('<div></div>').html(response.data);
  485. var new_content = new_content_wrapped.contents();
  486. // For legacy reasons, the effects processing code assumes that new_content
  487. // consists of a single top-level element. Also, it has not been
  488. // sufficiently tested whether attachBehaviors() can be successfully called
  489. // with a context object that includes top-level text nodes. However, to
  490. // give developers full control of the HTML appearing in the page, and to
  491. // enable Ajax content to be inserted in places where DIV elements are not
  492. // allowed (e.g., within TABLE, TR, and SPAN parents), we check if the new
  493. // content satisfies the requirement of a single top-level element, and
  494. // only use the container DIV created above when it doesn't. For more
  495. // information, please see http://drupal.org/node/736066.
  496. if (new_content.length != 1 || new_content.get(0).nodeType != 1) {
  497. new_content = new_content_wrapped;
  498. }
  499. // If removing content from the wrapper, detach behaviors first.
  500. switch (method) {
  501. case 'html':
  502. case 'replaceWith':
  503. case 'replaceAll':
  504. case 'empty':
  505. case 'remove':
  506. var settings = response.settings || ajax.settings || Drupal.settings;
  507. Drupal.detachBehaviors(wrapper, settings);
  508. }
  509. // Add the new content to the page.
  510. wrapper[method](new_content);
  511. // Immediately hide the new content if we're using any effects.
  512. if (effect.showEffect != 'show') {
  513. new_content.hide();
  514. }
  515. // Determine which effect to use and what content will receive the
  516. // effect, then show the new content.
  517. if ($('.ajax-new-content', new_content).length > 0) {
  518. $('.ajax-new-content', new_content).hide();
  519. new_content.show();
  520. $('.ajax-new-content', new_content)[effect.showEffect](effect.showSpeed);
  521. }
  522. else if (effect.showEffect != 'show') {
  523. new_content[effect.showEffect](effect.showSpeed);
  524. }
  525. // Attach all JavaScript behaviors to the new content, if it was successfully
  526. // added to the page, this if statement allows #ajax['wrapper'] to be
  527. // optional.
  528. if (new_content.parents('html').length > 0) {
  529. // Apply any settings from the returned JSON if available.
  530. var settings = response.settings || ajax.settings || Drupal.settings;
  531. Drupal.attachBehaviors(new_content, settings);
  532. }
  533. },
  534. /**
  535. * Command to remove a chunk from the page.
  536. */
  537. remove: function (ajax, response, status) {
  538. var settings = response.settings || ajax.settings || Drupal.settings;
  539. Drupal.detachBehaviors($(response.selector), settings);
  540. $(response.selector).remove();
  541. },
  542. /**
  543. * Command to mark a chunk changed.
  544. */
  545. changed: function (ajax, response, status) {
  546. if (!$(response.selector).hasClass('ajax-changed')) {
  547. $(response.selector).addClass('ajax-changed');
  548. if (response.asterisk) {
  549. $(response.selector).find(response.asterisk).append(' <span class="ajax-changed">*</span> ');
  550. }
  551. }
  552. },
  553. /**
  554. * Command to provide an alert.
  555. */
  556. alert: function (ajax, response, status) {
  557. alert(response.text, response.title);
  558. },
  559. /**
  560. * Command to provide the jQuery css() function.
  561. */
  562. css: function (ajax, response, status) {
  563. $(response.selector).css(response.argument);
  564. },
  565. /**
  566. * Command to set the settings that will be used for other commands in this response.
  567. */
  568. settings: function (ajax, response, status) {
  569. if (response.merge) {
  570. $.extend(true, Drupal.settings, response.settings);
  571. }
  572. else {
  573. ajax.settings = response.settings;
  574. }
  575. },
  576. /**
  577. * Command to attach data using jQuery's data API.
  578. */
  579. data: function (ajax, response, status) {
  580. $(response.selector).data(response.name, response.value);
  581. },
  582. /**
  583. * Command to apply a jQuery method.
  584. */
  585. invoke: function (ajax, response, status) {
  586. var $element = $(response.selector);
  587. $element[response.method].apply($element, response.arguments);
  588. },
  589. /**
  590. * Command to restripe a table.
  591. */
  592. restripe: function (ajax, response, status) {
  593. // :even and :odd are reversed because jQuery counts from 0 and
  594. // we count from 1, so we're out of sync.
  595. // Match immediate children of the parent element to allow nesting.
  596. $('> tbody > tr:visible, > tr:visible', $(response.selector))
  597. .removeClass('odd even')
  598. .filter(':even').addClass('odd').end()
  599. .filter(':odd').addClass('even');
  600. },
  601. /**
  602. * Command to add css.
  603. *
  604. * Uses the proprietary addImport method if available as browsers which
  605. * support that method ignore @import statements in dynamically added
  606. * stylesheets.
  607. */
  608. add_css: function (ajax, response, status) {
  609. // Add the styles in the normal way.
  610. $('head').prepend(response.data);
  611. // Add imports in the styles using the addImport method if available.
  612. var match, importMatch = /^@import url\("(.*)"\);$/igm;
  613. if (document.styleSheets[0].addImport && importMatch.test(response.data)) {
  614. importMatch.lastIndex = 0;
  615. while (match = importMatch.exec(response.data)) {
  616. document.styleSheets[0].addImport(match[1]);
  617. }
  618. }
  619. },
  620. /**
  621. * Command to update a form's build ID.
  622. */
  623. updateBuildId: function(ajax, response, status) {
  624. $('input[name="form_build_id"][value="' + response['old'] + '"]').val(response['new']);
  625. }
  626. };
  627. })(jQuery);