ajax.js 24 KB

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