ajax.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  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: 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. type: 'POST'
  179. };
  180. // For multipart forms (e.g., file uploads), jQuery Form targets the form
  181. // submission to an iframe instead of using an XHR object. The initial "src"
  182. // of the iframe, prior to the form submission, is set to options.iframeSrc.
  183. // "about:blank" is the semantically correct, standards-compliant, way to
  184. // initialize a blank iframe; however, some old IE versions (possibly only 6)
  185. // incorrectly report a mixed content warning when iframes with an
  186. // "about:blank" src are added to a parent document with an https:// origin.
  187. // jQuery Form works around this by defaulting to "javascript:false" instead,
  188. // but that breaks on Chrome 83, so here we force the semantically correct
  189. // behavior for all browsers except old IE.
  190. // @see https://www.drupal.org/project/drupal/issues/3143016
  191. // @see https://github.com/jquery-form/form/blob/df9cb101b9c9c085c8d75ad980c7ff1cf62063a1/jquery.form.js#L68
  192. // @see https://bugs.chromium.org/p/chromium/issues/detail?id=1084874
  193. // @see https://html.spec.whatwg.org/multipage/browsers.html#creating-browsing-contexts
  194. // @see https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
  195. if (navigator.userAgent.indexOf("MSIE") === -1) {
  196. ajax.options.iframeSrc = 'about:blank';
  197. }
  198. // Bind the ajaxSubmit function to the element event.
  199. $(ajax.element).bind(element_settings.event, function (event) {
  200. if (!Drupal.settings.urlIsAjaxTrusted[ajax.url] && !Drupal.urlIsLocal(ajax.url)) {
  201. throw new Error(Drupal.t('The callback URL is not local and not trusted: !url', {'!url': ajax.url}));
  202. }
  203. return ajax.eventResponse(this, event);
  204. });
  205. // If necessary, enable keyboard submission so that Ajax behaviors
  206. // can be triggered through keyboard input as well as e.g. a mousedown
  207. // action.
  208. if (element_settings.keypress) {
  209. $(ajax.element).keypress(function (event) {
  210. return ajax.keypressResponse(this, event);
  211. });
  212. }
  213. // If necessary, prevent the browser default action of an additional event.
  214. // For example, prevent the browser default action of a click, even if the
  215. // AJAX behavior binds to mousedown.
  216. if (element_settings.prevent) {
  217. $(ajax.element).bind(element_settings.prevent, false);
  218. }
  219. };
  220. /**
  221. * Handle a key press.
  222. *
  223. * The Ajax object will, if instructed, bind to a key press response. This
  224. * will test to see if the key press is valid to trigger this event and
  225. * if it is, trigger it for us and prevent other keypresses from triggering.
  226. * In this case we're handling RETURN and SPACEBAR keypresses (event codes 13
  227. * and 32. RETURN is often used to submit a form when in a textfield, and
  228. * SPACE is often used to activate an element without submitting.
  229. */
  230. Drupal.ajax.prototype.keypressResponse = function (element, event) {
  231. // Create a synonym for this to reduce code confusion.
  232. var ajax = this;
  233. // Detect enter key and space bar and allow the standard response for them,
  234. // except for form elements of type 'text' and 'textarea', where the
  235. // spacebar activation causes inappropriate activation if #ajax['keypress'] is
  236. // TRUE. On a text-type widget a space should always be a space.
  237. if (event.which == 13 || (event.which == 32 && element.type != 'text' && element.type != 'textarea')) {
  238. $(ajax.element_settings.element).trigger(ajax.element_settings.event);
  239. return false;
  240. }
  241. };
  242. /**
  243. * Handle an event that triggers an Ajax response.
  244. *
  245. * When an event that triggers an Ajax response happens, this method will
  246. * perform the actual Ajax call. It is bound to the event using
  247. * bind() in the constructor, and it uses the options specified on the
  248. * ajax object.
  249. */
  250. Drupal.ajax.prototype.eventResponse = function (element, event) {
  251. // Create a synonym for this to reduce code confusion.
  252. var ajax = this;
  253. // Do not perform another ajax command if one is already in progress.
  254. if (ajax.ajaxing) {
  255. return false;
  256. }
  257. try {
  258. if (ajax.form) {
  259. // If setClick is set, we must set this to ensure that the button's
  260. // value is passed.
  261. if (ajax.setClick) {
  262. // Mark the clicked button. 'form.clk' is a special variable for
  263. // ajaxSubmit that tells the system which element got clicked to
  264. // trigger the submit. Without it there would be no 'op' or
  265. // equivalent.
  266. element.form.clk = element;
  267. }
  268. ajax.form.ajaxSubmit(ajax.options);
  269. }
  270. else {
  271. ajax.beforeSerialize(ajax.element, ajax.options);
  272. $.ajax(ajax.options);
  273. }
  274. }
  275. catch (e) {
  276. // Unset the ajax.ajaxing flag here because it won't be unset during
  277. // the complete response.
  278. ajax.ajaxing = false;
  279. alert("An error occurred while attempting to process " + ajax.options.url + ": " + e.message);
  280. }
  281. // For radio/checkbox, allow the default event. On IE, this means letting
  282. // it actually check the box.
  283. if (typeof element.type != 'undefined' && (element.type == 'checkbox' || element.type == 'radio')) {
  284. return true;
  285. }
  286. else {
  287. return false;
  288. }
  289. };
  290. /**
  291. * Handler for the form serialization.
  292. *
  293. * Runs before the beforeSend() handler (see below), and unlike that one, runs
  294. * before field data is collected.
  295. */
  296. Drupal.ajax.prototype.beforeSerialize = function (element, options) {
  297. // Allow detaching behaviors to update field values before collecting them.
  298. // This is only needed when field values are added to the POST data, so only
  299. // when there is a form such that this.form.ajaxSubmit() is used instead of
  300. // $.ajax(). When there is no form and $.ajax() is used, beforeSerialize()
  301. // isn't called, but don't rely on that: explicitly check this.form.
  302. if (this.form) {
  303. var settings = this.settings || Drupal.settings;
  304. Drupal.detachBehaviors(this.form, settings, 'serialize');
  305. }
  306. // Prevent duplicate HTML ids in the returned markup.
  307. // @see drupal_html_id()
  308. options.data['ajax_html_ids[]'] = [];
  309. $('[id]').each(function () {
  310. options.data['ajax_html_ids[]'].push(this.id);
  311. });
  312. // Allow Drupal to return new JavaScript and CSS files to load without
  313. // returning the ones already loaded.
  314. // @see ajax_base_page_theme()
  315. // @see drupal_get_css()
  316. // @see drupal_get_js()
  317. options.data['ajax_page_state[theme]'] = Drupal.settings.ajaxPageState.theme;
  318. options.data['ajax_page_state[theme_token]'] = Drupal.settings.ajaxPageState.theme_token;
  319. for (var key in Drupal.settings.ajaxPageState.css) {
  320. options.data['ajax_page_state[css][' + key + ']'] = 1;
  321. }
  322. for (var key in Drupal.settings.ajaxPageState.js) {
  323. options.data['ajax_page_state[js][' + key + ']'] = 1;
  324. }
  325. };
  326. /**
  327. * Modify form values prior to form submission.
  328. */
  329. Drupal.ajax.prototype.beforeSubmit = function (form_values, element, options) {
  330. // This function is left empty to make it simple to override for modules
  331. // that wish to add functionality here.
  332. };
  333. /**
  334. * Prepare the Ajax request before it is sent.
  335. */
  336. Drupal.ajax.prototype.beforeSend = function (xmlhttprequest, options) {
  337. // For forms without file inputs, the jQuery Form plugin serializes the form
  338. // values, and then calls jQuery's $.ajax() function, which invokes this
  339. // handler. In this circumstance, options.extraData is never used. For forms
  340. // with file inputs, the jQuery Form plugin uses the browser's normal form
  341. // submission mechanism, but captures the response in a hidden IFRAME. In this
  342. // circumstance, it calls this handler first, and then appends hidden fields
  343. // to the form to submit the values in options.extraData. There is no simple
  344. // way to know which submission mechanism will be used, so we add to extraData
  345. // regardless, and allow it to be ignored in the former case.
  346. if (this.form) {
  347. options.extraData = options.extraData || {};
  348. // Let the server know when the IFRAME submission mechanism is used. The
  349. // server can use this information to wrap the JSON response in a TEXTAREA,
  350. // as per http://jquery.malsup.com/form/#file-upload.
  351. options.extraData.ajax_iframe_upload = '1';
  352. // The triggering element is about to be disabled (see below), but if it
  353. // contains a value (e.g., a checkbox, textfield, select, etc.), ensure that
  354. // value is included in the submission. As per above, submissions that use
  355. // $.ajax() are already serialized prior to the element being disabled, so
  356. // this is only needed for IFRAME submissions.
  357. var v = $.fieldValue(this.element);
  358. if (v !== null) {
  359. options.extraData[this.element.name] = Drupal.checkPlain(v);
  360. }
  361. }
  362. // Disable the element that received the change to prevent user interface
  363. // interaction while the Ajax request is in progress. ajax.ajaxing prevents
  364. // the element from triggering a new request, but does not prevent the user
  365. // from changing its value.
  366. $(this.element).addClass('progress-disabled').attr('disabled', true);
  367. // Insert progressbar or throbber.
  368. if (this.progress.type == 'bar') {
  369. var progressBar = new Drupal.progressBar('ajax-progress-' + this.element.id, eval(this.progress.update_callback), this.progress.method, eval(this.progress.error_callback));
  370. if (this.progress.message) {
  371. progressBar.setProgress(-1, this.progress.message);
  372. }
  373. if (this.progress.url) {
  374. progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500);
  375. }
  376. this.progress.element = $(progressBar.element).addClass('ajax-progress ajax-progress-bar');
  377. this.progress.object = progressBar;
  378. $(this.element).after(this.progress.element);
  379. }
  380. else if (this.progress.type == 'throbber') {
  381. this.progress.element = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber">&nbsp;</div></div>');
  382. if (this.progress.message) {
  383. $('.throbber', this.progress.element).after('<div class="message">' + this.progress.message + '</div>');
  384. }
  385. $(this.element).after(this.progress.element);
  386. }
  387. };
  388. /**
  389. * Handler for the form redirection completion.
  390. */
  391. Drupal.ajax.prototype.success = function (response, status) {
  392. // Remove the progress element.
  393. if (this.progress.element) {
  394. $(this.progress.element).remove();
  395. }
  396. if (this.progress.object) {
  397. this.progress.object.stopMonitoring();
  398. }
  399. $(this.element).removeClass('progress-disabled').removeAttr('disabled');
  400. Drupal.freezeHeight();
  401. for (var i in response) {
  402. if (response.hasOwnProperty(i) && response[i]['command'] && this.commands[response[i]['command']]) {
  403. this.commands[response[i]['command']](this, response[i], status);
  404. }
  405. }
  406. // Reattach behaviors, if they were detached in beforeSerialize(). The
  407. // attachBehaviors() called on the new content from processing the response
  408. // commands is not sufficient, because behaviors from the entire form need
  409. // to be reattached.
  410. if (this.form) {
  411. var settings = this.settings || Drupal.settings;
  412. Drupal.attachBehaviors(this.form, settings);
  413. }
  414. Drupal.unfreezeHeight();
  415. // Remove any response-specific settings so they don't get used on the next
  416. // call by mistake.
  417. this.settings = null;
  418. };
  419. /**
  420. * Build an effect object which tells us how to apply the effect when adding new HTML.
  421. */
  422. Drupal.ajax.prototype.getEffect = function (response) {
  423. var type = response.effect || this.effect;
  424. var speed = response.speed || this.speed;
  425. var effect = {};
  426. if (type == 'none') {
  427. effect.showEffect = 'show';
  428. effect.hideEffect = 'hide';
  429. effect.showSpeed = '';
  430. }
  431. else if (type == 'fade') {
  432. effect.showEffect = 'fadeIn';
  433. effect.hideEffect = 'fadeOut';
  434. effect.showSpeed = speed;
  435. }
  436. else {
  437. effect.showEffect = type + 'Toggle';
  438. effect.hideEffect = type + 'Toggle';
  439. effect.showSpeed = speed;
  440. }
  441. return effect;
  442. };
  443. /**
  444. * Handler for the form redirection error.
  445. */
  446. Drupal.ajax.prototype.error = function (xmlhttprequest, uri, customMessage) {
  447. Drupal.displayAjaxError(Drupal.ajaxError(xmlhttprequest, uri, customMessage));
  448. // Remove the progress element.
  449. if (this.progress.element) {
  450. $(this.progress.element).remove();
  451. }
  452. if (this.progress.object) {
  453. this.progress.object.stopMonitoring();
  454. }
  455. // Undo hide.
  456. $(this.wrapper).show();
  457. // Re-enable the element.
  458. $(this.element).removeClass('progress-disabled').removeAttr('disabled');
  459. // Reattach behaviors, if they were detached in beforeSerialize().
  460. if (this.form) {
  461. var settings = this.settings || Drupal.settings;
  462. Drupal.attachBehaviors(this.form, settings);
  463. }
  464. };
  465. /**
  466. * Provide a series of commands that the server can request the client perform.
  467. */
  468. Drupal.ajax.prototype.commands = {
  469. /**
  470. * Command to insert new content into the DOM.
  471. */
  472. insert: function (ajax, response, status) {
  473. // Get information from the response. If it is not there, default to
  474. // our presets.
  475. var wrapper = response.selector ? $(response.selector) : $(ajax.wrapper);
  476. var method = response.method || ajax.method;
  477. var effect = ajax.getEffect(response);
  478. // We don't know what response.data contains: it might be a string of text
  479. // without HTML, so don't rely on jQuery correctly iterpreting
  480. // $(response.data) as new HTML rather than a CSS selector. Also, if
  481. // response.data contains top-level text nodes, they get lost with either
  482. // $(response.data) or $('<div></div>').replaceWith(response.data).
  483. var new_content_wrapped = $('<div></div>').html(response.data);
  484. var new_content = new_content_wrapped.contents();
  485. // For legacy reasons, the effects processing code assumes that new_content
  486. // consists of a single top-level element. Also, it has not been
  487. // sufficiently tested whether attachBehaviors() can be successfully called
  488. // with a context object that includes top-level text nodes. However, to
  489. // give developers full control of the HTML appearing in the page, and to
  490. // enable Ajax content to be inserted in places where DIV elements are not
  491. // allowed (e.g., within TABLE, TR, and SPAN parents), we check if the new
  492. // content satisfies the requirement of a single top-level element, and
  493. // only use the container DIV created above when it doesn't. For more
  494. // information, please see http://drupal.org/node/736066.
  495. if (new_content.length != 1 || new_content.get(0).nodeType != 1) {
  496. new_content = new_content_wrapped;
  497. }
  498. // If removing content from the wrapper, detach behaviors first.
  499. switch (method) {
  500. case 'html':
  501. case 'replaceWith':
  502. case 'replaceAll':
  503. case 'empty':
  504. case 'remove':
  505. var settings = response.settings || ajax.settings || Drupal.settings;
  506. Drupal.detachBehaviors(wrapper, settings);
  507. }
  508. // Add the new content to the page.
  509. wrapper[method](new_content);
  510. // Immediately hide the new content if we're using any effects.
  511. if (effect.showEffect != 'show') {
  512. new_content.hide();
  513. }
  514. // Determine which effect to use and what content will receive the
  515. // effect, then show the new content.
  516. if ($('.ajax-new-content', new_content).length > 0) {
  517. $('.ajax-new-content', new_content).hide();
  518. new_content.show();
  519. $('.ajax-new-content', new_content)[effect.showEffect](effect.showSpeed);
  520. }
  521. else if (effect.showEffect != 'show') {
  522. new_content[effect.showEffect](effect.showSpeed);
  523. }
  524. // Attach all JavaScript behaviors to the new content, if it was successfully
  525. // added to the page, this if statement allows #ajax['wrapper'] to be
  526. // optional.
  527. if (new_content.parents('html').length > 0) {
  528. // Apply any settings from the returned JSON if available.
  529. var settings = response.settings || ajax.settings || Drupal.settings;
  530. Drupal.attachBehaviors(new_content, settings);
  531. }
  532. },
  533. /**
  534. * Command to remove a chunk from the page.
  535. */
  536. remove: function (ajax, response, status) {
  537. var settings = response.settings || ajax.settings || Drupal.settings;
  538. Drupal.detachBehaviors($(response.selector), settings);
  539. $(response.selector).remove();
  540. },
  541. /**
  542. * Command to mark a chunk changed.
  543. */
  544. changed: function (ajax, response, status) {
  545. if (!$(response.selector).hasClass('ajax-changed')) {
  546. $(response.selector).addClass('ajax-changed');
  547. if (response.asterisk) {
  548. $(response.selector).find(response.asterisk).append(' <span class="ajax-changed">*</span> ');
  549. }
  550. }
  551. },
  552. /**
  553. * Command to provide an alert.
  554. */
  555. alert: function (ajax, response, status) {
  556. alert(response.text, response.title);
  557. },
  558. /**
  559. * Command to provide the jQuery css() function.
  560. */
  561. css: function (ajax, response, status) {
  562. $(response.selector).css(response.argument);
  563. },
  564. /**
  565. * Command to set the settings that will be used for other commands in this response.
  566. */
  567. settings: function (ajax, response, status) {
  568. if (response.merge) {
  569. $.extend(true, Drupal.settings, response.settings);
  570. }
  571. else {
  572. ajax.settings = response.settings;
  573. }
  574. },
  575. /**
  576. * Command to attach data using jQuery's data API.
  577. */
  578. data: function (ajax, response, status) {
  579. $(response.selector).data(response.name, response.value);
  580. },
  581. /**
  582. * Command to apply a jQuery method.
  583. */
  584. invoke: function (ajax, response, status) {
  585. var $element = $(response.selector);
  586. $element[response.method].apply($element, response.arguments);
  587. },
  588. /**
  589. * Command to restripe a table.
  590. */
  591. restripe: function (ajax, response, status) {
  592. // :even and :odd are reversed because jQuery counts from 0 and
  593. // we count from 1, so we're out of sync.
  594. // Match immediate children of the parent element to allow nesting.
  595. $('> tbody > tr:visible, > tr:visible', $(response.selector))
  596. .removeClass('odd even')
  597. .filter(':even').addClass('odd').end()
  598. .filter(':odd').addClass('even');
  599. },
  600. /**
  601. * Command to add css.
  602. *
  603. * Uses the proprietary addImport method if available as browsers which
  604. * support that method ignore @import statements in dynamically added
  605. * stylesheets.
  606. */
  607. add_css: function (ajax, response, status) {
  608. // Add the styles in the normal way.
  609. $('head').prepend(response.data);
  610. // Add imports in the styles using the addImport method if available.
  611. var match, importMatch = /^@import url\("(.*)"\);$/igm;
  612. if (document.styleSheets[0].addImport && importMatch.test(response.data)) {
  613. importMatch.lastIndex = 0;
  614. while (match = importMatch.exec(response.data)) {
  615. document.styleSheets[0].addImport(match[1]);
  616. }
  617. }
  618. },
  619. /**
  620. * Command to update a form's build ID.
  621. */
  622. updateBuildId: function(ajax, response, status) {
  623. $('input[name="form_build_id"][value="' + response['old'] + '"]').val(response['new']);
  624. }
  625. };
  626. })(jQuery);