jquery_ujs.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. (function($, undefined) {
  2. /**
  3. * Unobtrusive scripting adapter for jQuery
  4. * https://github.com/rails/jquery-ujs
  5. *
  6. * Requires jQuery 1.8.0 or later.
  7. *
  8. * Released under the MIT license
  9. *
  10. */
  11. // Cut down on the number of issues from people inadvertently including jquery_ujs twice
  12. // by detecting and raising an error when it happens.
  13. if ( $.rails !== undefined ) {
  14. $.error('jquery-ujs has already been loaded!');
  15. }
  16. // Shorthand to make it a little easier to call public rails functions from within rails.js
  17. var rails;
  18. var $document = $(document);
  19. $.rails = rails = {
  20. // Link elements bound by jquery-ujs
  21. linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote], a[data-disable-with], a[data-disable]',
  22. // Button elements bound by jquery-ujs
  23. buttonClickSelector: 'button[data-remote]:not(form button), button[data-confirm]:not(form button)',
  24. // Select elements bound by jquery-ujs
  25. inputChangeSelector: 'select[data-remote], input[data-remote], textarea[data-remote]',
  26. // Form elements bound by jquery-ujs
  27. formSubmitSelector: 'form',
  28. // Form input elements bound by jquery-ujs
  29. formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type]), input[type=submit][form], input[type=image][form], button[type=submit][form], button[form]:not([type])',
  30. // Form input elements disabled during form submission
  31. disableSelector: 'input[data-disable-with]:enabled, button[data-disable-with]:enabled, textarea[data-disable-with]:enabled, input[data-disable]:enabled, button[data-disable]:enabled, textarea[data-disable]:enabled',
  32. // Form input elements re-enabled after form submission
  33. enableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled, input[data-disable]:disabled, button[data-disable]:disabled, textarea[data-disable]:disabled',
  34. // Form required input elements
  35. requiredInputSelector: 'input[name][required]:not([disabled]),textarea[name][required]:not([disabled])',
  36. // Form file input elements
  37. fileInputSelector: 'input[type=file]',
  38. // Link onClick disable selector with possible reenable after remote submission
  39. linkDisableSelector: 'a[data-disable-with], a[data-disable]',
  40. // Button onClick disable selector with possible reenable after remote submission
  41. buttonDisableSelector: 'button[data-remote][data-disable-with], button[data-remote][data-disable]',
  42. // Make sure that every Ajax request sends the CSRF token
  43. CSRFProtection: function(xhr) {
  44. var token = $('meta[name="csrf-token"]').attr('content');
  45. if (token) xhr.setRequestHeader('X-CSRF-Token', token);
  46. },
  47. // making sure that all forms have actual up-to-date token(cached forms contain old one)
  48. refreshCSRFTokens: function(){
  49. var csrfToken = $('meta[name=csrf-token]').attr('content');
  50. var csrfParam = $('meta[name=csrf-param]').attr('content');
  51. $('form input[name="' + csrfParam + '"]').val(csrfToken);
  52. },
  53. // Triggers an event on an element and returns false if the event result is false
  54. fire: function(obj, name, data) {
  55. var event = $.Event(name);
  56. obj.trigger(event, data);
  57. return event.result !== false;
  58. },
  59. // Default confirm dialog, may be overridden with custom confirm dialog in $.rails.confirm
  60. confirm: function(message) {
  61. return confirm(message);
  62. },
  63. // Default ajax function, may be overridden with custom function in $.rails.ajax
  64. ajax: function(options) {
  65. return $.ajax(options);
  66. },
  67. // Default way to get an element's href. May be overridden at $.rails.href.
  68. href: function(element) {
  69. return element.attr('href');
  70. },
  71. // Submits "remote" forms and links with ajax
  72. handleRemote: function(element) {
  73. var method, url, data, elCrossDomain, crossDomain, withCredentials, dataType, options;
  74. if (rails.fire(element, 'ajax:before')) {
  75. elCrossDomain = element.data('cross-domain');
  76. crossDomain = elCrossDomain === undefined ? null : elCrossDomain;
  77. withCredentials = element.data('with-credentials') || null;
  78. dataType = element.data('type') || ($.ajaxSettings && $.ajaxSettings.dataType);
  79. if (element.is('form')) {
  80. method = element.attr('method');
  81. url = element.attr('action');
  82. data = element.serializeArray();
  83. // memoized value from clicked submit button
  84. var button = element.data('ujs:submit-button');
  85. if (button) {
  86. data.push(button);
  87. element.data('ujs:submit-button', null);
  88. }
  89. } else if (element.is(rails.inputChangeSelector)) {
  90. method = element.data('method');
  91. url = element.data('url');
  92. data = element.serialize();
  93. if (element.data('params')) data = data + "&" + element.data('params');
  94. } else if (element.is(rails.buttonClickSelector)) {
  95. method = element.data('method') || 'get';
  96. url = element.data('url');
  97. data = element.serialize();
  98. if (element.data('params')) data = data + "&" + element.data('params');
  99. } else {
  100. method = element.data('method');
  101. url = rails.href(element);
  102. data = element.data('params') || null;
  103. }
  104. options = {
  105. type: method || 'GET', data: data, dataType: dataType,
  106. // stopping the "ajax:beforeSend" event will cancel the ajax request
  107. beforeSend: function(xhr, settings) {
  108. if (settings.dataType === undefined) {
  109. xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
  110. }
  111. if (rails.fire(element, 'ajax:beforeSend', [xhr, settings])) {
  112. element.trigger('ajax:send', xhr);
  113. } else {
  114. return false;
  115. }
  116. },
  117. success: function(data, status, xhr) {
  118. element.trigger('ajax:success', [data, status, xhr]);
  119. },
  120. complete: function(xhr, status) {
  121. element.trigger('ajax:complete', [xhr, status]);
  122. },
  123. error: function(xhr, status, error) {
  124. element.trigger('ajax:error', [xhr, status, error]);
  125. },
  126. crossDomain: crossDomain
  127. };
  128. // There is no withCredentials for IE6-8 when
  129. // "Enable native XMLHTTP support" is disabled
  130. if (withCredentials) {
  131. options.xhrFields = {
  132. withCredentials: withCredentials
  133. };
  134. }
  135. // Only pass url to `ajax` options if not blank
  136. if (url) { options.url = url; }
  137. return rails.ajax(options);
  138. } else {
  139. return false;
  140. }
  141. },
  142. // Handles "data-method" on links such as:
  143. // <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a>
  144. handleMethod: function(link) {
  145. var href = rails.href(link),
  146. method = link.data('method'),
  147. target = link.attr('target'),
  148. csrfToken = $('meta[name=csrf-token]').attr('content'),
  149. csrfParam = $('meta[name=csrf-param]').attr('content'),
  150. form = $('<form method="post" action="' + href + '"></form>'),
  151. metadataInput = '<input name="_method" value="' + method + '" type="hidden" />';
  152. if (csrfParam !== undefined && csrfToken !== undefined) {
  153. metadataInput += '<input name="' + csrfParam + '" value="' + csrfToken + '" type="hidden" />';
  154. }
  155. if (target) { form.attr('target', target); }
  156. form.hide().append(metadataInput).appendTo('body');
  157. form.submit();
  158. },
  159. // Helper function that returns form elements that match the specified CSS selector
  160. // If form is actually a "form" element this will return associated elements outside the from that have
  161. // the html form attribute set
  162. formElements: function(form, selector) {
  163. return form.is('form') ? $(form[0].elements).filter(selector) : form.find(selector);
  164. },
  165. /* Disables form elements:
  166. - Caches element value in 'ujs:enable-with' data store
  167. - Replaces element text with value of 'data-disable-with' attribute
  168. - Sets disabled property to true
  169. */
  170. disableFormElements: function(form) {
  171. rails.formElements(form, rails.disableSelector).each(function() {
  172. rails.disableFormElement($(this));
  173. });
  174. },
  175. disableFormElement: function(element) {
  176. var method, replacement;
  177. method = element.is('button') ? 'html' : 'val';
  178. replacement = element.data('disable-with');
  179. element.data('ujs:enable-with', element[method]());
  180. if (replacement !== undefined) {
  181. element[method](replacement);
  182. }
  183. element.prop('disabled', true);
  184. },
  185. /* Re-enables disabled form elements:
  186. - Replaces element text with cached value from 'ujs:enable-with' data store (created in `disableFormElements`)
  187. - Sets disabled property to false
  188. */
  189. enableFormElements: function(form) {
  190. rails.formElements(form, rails.enableSelector).each(function() {
  191. rails.enableFormElement($(this));
  192. });
  193. },
  194. enableFormElement: function(element) {
  195. var method = element.is('button') ? 'html' : 'val';
  196. if (element.data('ujs:enable-with')) element[method](element.data('ujs:enable-with'));
  197. element.prop('disabled', false);
  198. },
  199. /* For 'data-confirm' attribute:
  200. - Fires `confirm` event
  201. - Shows the confirmation dialog
  202. - Fires the `confirm:complete` event
  203. Returns `true` if no function stops the chain and user chose yes; `false` otherwise.
  204. Attaching a handler to the element's `confirm` event that returns a `falsy` value cancels the confirmation dialog.
  205. Attaching a handler to the element's `confirm:complete` event that returns a `falsy` value makes this function
  206. return false. The `confirm:complete` event is fired whether or not the user answered true or false to the dialog.
  207. */
  208. allowAction: function(element) {
  209. var message = element.data('confirm'),
  210. answer = false, callback;
  211. if (!message) { return true; }
  212. if (rails.fire(element, 'confirm')) {
  213. answer = rails.confirm(message);
  214. callback = rails.fire(element, 'confirm:complete', [answer]);
  215. }
  216. return answer && callback;
  217. },
  218. // Helper function which checks for blank inputs in a form that match the specified CSS selector
  219. blankInputs: function(form, specifiedSelector, nonBlank) {
  220. var inputs = $(), input, valueToCheck,
  221. selector = specifiedSelector || 'input,textarea',
  222. allInputs = form.find(selector);
  223. allInputs.each(function() {
  224. input = $(this);
  225. valueToCheck = input.is('input[type=checkbox],input[type=radio]') ? input.is(':checked') : input.val();
  226. // If nonBlank and valueToCheck are both truthy, or nonBlank and valueToCheck are both falsey
  227. if (!valueToCheck === !nonBlank) {
  228. // Don't count unchecked required radio if other radio with same name is checked
  229. if (input.is('input[type=radio]') && allInputs.filter('input[type=radio]:checked[name="' + input.attr('name') + '"]').length) {
  230. return true; // Skip to next input
  231. }
  232. inputs = inputs.add(input);
  233. }
  234. });
  235. return inputs.length ? inputs : false;
  236. },
  237. // Helper function which checks for non-blank inputs in a form that match the specified CSS selector
  238. nonBlankInputs: function(form, specifiedSelector) {
  239. return rails.blankInputs(form, specifiedSelector, true); // true specifies nonBlank
  240. },
  241. // Helper function, needed to provide consistent behavior in IE
  242. stopEverything: function(e) {
  243. $(e.target).trigger('ujs:everythingStopped');
  244. e.stopImmediatePropagation();
  245. return false;
  246. },
  247. // replace element's html with the 'data-disable-with' after storing original html
  248. // and prevent clicking on it
  249. disableElement: function(element) {
  250. var replacement = element.data('disable-with');
  251. element.data('ujs:enable-with', element.html()); // store enabled state
  252. if (replacement !== undefined) {
  253. element.html(replacement);
  254. }
  255. element.bind('click.railsDisable', function(e) { // prevent further clicking
  256. return rails.stopEverything(e);
  257. });
  258. },
  259. // restore element to its original state which was disabled by 'disableElement' above
  260. enableElement: function(element) {
  261. if (element.data('ujs:enable-with') !== undefined) {
  262. element.html(element.data('ujs:enable-with')); // set to old enabled state
  263. element.removeData('ujs:enable-with'); // clean up cache
  264. }
  265. element.unbind('click.railsDisable'); // enable element
  266. }
  267. };
  268. if (rails.fire($document, 'rails:attachBindings')) {
  269. $.ajaxPrefilter(function(options, originalOptions, xhr){ if ( !options.crossDomain ) { rails.CSRFProtection(xhr); }});
  270. // This event works the same as the load event, except that it fires every
  271. // time the page is loaded.
  272. //
  273. // See https://github.com/rails/jquery-ujs/issues/357
  274. // See https://developer.mozilla.org/en-US/docs/Using_Firefox_1.5_caching
  275. $(window).on("pageshow.rails", function () {
  276. $($.rails.enableSelector).each(function () {
  277. var element = $(this);
  278. if (element.data("ujs:enable-with")) {
  279. $.rails.enableFormElement(element);
  280. }
  281. });
  282. $($.rails.linkDisableSelector).each(function () {
  283. var element = $(this);
  284. if (element.data("ujs:enable-with")) {
  285. $.rails.enableElement(element);
  286. }
  287. });
  288. });
  289. $document.delegate(rails.linkDisableSelector, 'ajax:complete', function() {
  290. rails.enableElement($(this));
  291. });
  292. $document.delegate(rails.buttonDisableSelector, 'ajax:complete', function() {
  293. rails.enableFormElement($(this));
  294. });
  295. $document.delegate(rails.linkClickSelector, 'click.rails', function(e) {
  296. var link = $(this), method = link.data('method'), data = link.data('params'), metaClick = e.metaKey || e.ctrlKey;
  297. if (!rails.allowAction(link)) return rails.stopEverything(e);
  298. if (!metaClick && link.is(rails.linkDisableSelector)) rails.disableElement(link);
  299. if (link.data('remote') !== undefined) {
  300. if (metaClick && (!method || method === 'GET') && !data) { return true; }
  301. var handleRemote = rails.handleRemote(link);
  302. // response from rails.handleRemote() will either be false or a deferred object promise.
  303. if (handleRemote === false) {
  304. rails.enableElement(link);
  305. } else {
  306. handleRemote.error( function() { rails.enableElement(link); } );
  307. }
  308. return false;
  309. } else if (link.data('method')) {
  310. rails.handleMethod(link);
  311. return false;
  312. }
  313. });
  314. $document.delegate(rails.buttonClickSelector, 'click.rails', function(e) {
  315. var button = $(this);
  316. if (!rails.allowAction(button)) return rails.stopEverything(e);
  317. if (button.is(rails.buttonDisableSelector)) rails.disableFormElement(button);
  318. var handleRemote = rails.handleRemote(button);
  319. // response from rails.handleRemote() will either be false or a deferred object promise.
  320. if (handleRemote === false) {
  321. rails.enableFormElement(button);
  322. } else {
  323. handleRemote.error( function() { rails.enableFormElement(button); } );
  324. }
  325. return false;
  326. });
  327. $document.delegate(rails.inputChangeSelector, 'change.rails', function(e) {
  328. var link = $(this);
  329. if (!rails.allowAction(link)) return rails.stopEverything(e);
  330. rails.handleRemote(link);
  331. return false;
  332. });
  333. $document.delegate(rails.formSubmitSelector, 'submit.rails', function(e) {
  334. var form = $(this),
  335. remote = form.data('remote') !== undefined,
  336. blankRequiredInputs,
  337. nonBlankFileInputs;
  338. if (!rails.allowAction(form)) return rails.stopEverything(e);
  339. // skip other logic when required values are missing or file upload is present
  340. if (form.attr('novalidate') == undefined) {
  341. blankRequiredInputs = rails.blankInputs(form, rails.requiredInputSelector);
  342. if (blankRequiredInputs && rails.fire(form, 'ajax:aborted:required', [blankRequiredInputs])) {
  343. return rails.stopEverything(e);
  344. }
  345. }
  346. if (remote) {
  347. nonBlankFileInputs = rails.nonBlankInputs(form, rails.fileInputSelector);
  348. if (nonBlankFileInputs) {
  349. // slight timeout so that the submit button gets properly serialized
  350. // (make it easy for event handler to serialize form without disabled values)
  351. setTimeout(function(){ rails.disableFormElements(form); }, 13);
  352. var aborted = rails.fire(form, 'ajax:aborted:file', [nonBlankFileInputs]);
  353. // re-enable form elements if event bindings return false (canceling normal form submission)
  354. if (!aborted) { setTimeout(function(){ rails.enableFormElements(form); }, 13); }
  355. return aborted;
  356. }
  357. rails.handleRemote(form);
  358. return false;
  359. } else {
  360. // slight timeout so that the submit button gets properly serialized
  361. setTimeout(function(){ rails.disableFormElements(form); }, 13);
  362. }
  363. });
  364. $document.delegate(rails.formInputClickSelector, 'click.rails', function(event) {
  365. var button = $(this);
  366. if (!rails.allowAction(button)) return rails.stopEverything(event);
  367. // register the pressed submit button
  368. var name = button.attr('name'),
  369. data = name ? {name:name, value:button.val()} : null;
  370. button.closest('form').data('ujs:submit-button', data);
  371. });
  372. $document.delegate(rails.formSubmitSelector, 'ajax:send.rails', function(event) {
  373. if (this == event.target) rails.disableFormElements($(this));
  374. });
  375. $document.delegate(rails.formSubmitSelector, 'ajax:complete.rails', function(event) {
  376. if (this == event.target) rails.enableFormElements($(this));
  377. });
  378. $(function(){
  379. rails.refreshCSRFTokens();
  380. });
  381. }
  382. })( jQuery );