jquery.form.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  1. /*!
  2. * jQuery Form Plugin
  3. * version: 3.51.0-2014.06.20
  4. * Requires jQuery v1.5 or later
  5. * Copyright (c) 2014 M. Alsup
  6. * Examples and documentation at: http://malsup.com/jquery/form/
  7. * Project repository: https://github.com/malsup/form
  8. * Dual licensed under the MIT and GPL licenses.
  9. * https://github.com/malsup/form#copyright-and-license
  10. */
  11. /*global ActiveXObject */
  12. // AMD support
  13. (function (factory) {
  14. "use strict";
  15. if (typeof define === 'function' && define.amd) {
  16. // using AMD; register as anon module
  17. define(['jquery'], factory);
  18. } else {
  19. // no AMD; invoke directly
  20. factory( (typeof(jQuery) != 'undefined') ? jQuery : window.Zepto );
  21. }
  22. }
  23. (function($) {
  24. "use strict";
  25. /*
  26. Usage Note:
  27. -----------
  28. Do not use both ajaxSubmit and ajaxForm on the same form. These
  29. functions are mutually exclusive. Use ajaxSubmit if you want
  30. to bind your own submit handler to the form. For example,
  31. $(document).ready(function() {
  32. $('#myForm').on('submit', function(e) {
  33. e.preventDefault(); // <-- important
  34. $(this).ajaxSubmit({
  35. target: '#output'
  36. });
  37. });
  38. });
  39. Use ajaxForm when you want the plugin to manage all the event binding
  40. for you. For example,
  41. $(document).ready(function() {
  42. $('#myForm').ajaxForm({
  43. target: '#output'
  44. });
  45. });
  46. You can also use ajaxForm with delegation (requires jQuery v1.7+), so the
  47. form does not have to exist when you invoke ajaxForm:
  48. $('#myForm').ajaxForm({
  49. delegation: true,
  50. target: '#output'
  51. });
  52. When using ajaxForm, the ajaxSubmit function will be invoked for you
  53. at the appropriate time.
  54. */
  55. /**
  56. * Feature detection
  57. */
  58. var feature = {};
  59. feature.fileapi = $("<input type='file'/>").get(0).files !== undefined;
  60. feature.formdata = window.FormData !== undefined;
  61. var hasProp = !!$.fn.prop;
  62. // attr2 uses prop when it can but checks the return type for
  63. // an expected string. this accounts for the case where a form
  64. // contains inputs with names like "action" or "method"; in those
  65. // cases "prop" returns the element
  66. $.fn.attr2 = function() {
  67. if ( ! hasProp ) {
  68. return this.attr.apply(this, arguments);
  69. }
  70. var val = this.prop.apply(this, arguments);
  71. if ( ( val && val.jquery ) || typeof val === 'string' ) {
  72. return val;
  73. }
  74. return this.attr.apply(this, arguments);
  75. };
  76. /**
  77. * ajaxSubmit() provides a mechanism for immediately submitting
  78. * an HTML form using AJAX.
  79. */
  80. $.fn.ajaxSubmit = function(options) {
  81. /*jshint scripturl:true */
  82. // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
  83. if (!this.length) {
  84. log('ajaxSubmit: skipping submit process - no element selected');
  85. return this;
  86. }
  87. var method, action, url, $form = this;
  88. if (typeof options == 'function') {
  89. options = { success: options };
  90. }
  91. else if ( options === undefined ) {
  92. options = {};
  93. }
  94. method = options.type || this.attr2('method');
  95. action = options.url || this.attr2('action');
  96. url = (typeof action === 'string') ? $.trim(action) : '';
  97. url = url || window.location.href || '';
  98. if (url) {
  99. // clean url (don't include hash vaue)
  100. url = (url.match(/^([^#]+)/)||[])[1];
  101. }
  102. options = $.extend(true, {
  103. url: url,
  104. success: $.ajaxSettings.success,
  105. type: method || $.ajaxSettings.type,
  106. iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
  107. }, options);
  108. // hook for manipulating the form data before it is extracted;
  109. // convenient for use with rich editors like tinyMCE or FCKEditor
  110. var veto = {};
  111. this.trigger('form-pre-serialize', [this, options, veto]);
  112. if (veto.veto) {
  113. log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
  114. return this;
  115. }
  116. // provide opportunity to alter form data before it is serialized
  117. if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
  118. log('ajaxSubmit: submit aborted via beforeSerialize callback');
  119. return this;
  120. }
  121. var traditional = options.traditional;
  122. if ( traditional === undefined ) {
  123. traditional = $.ajaxSettings.traditional;
  124. }
  125. var elements = [];
  126. var qx, a = this.formToArray(options.semantic, elements);
  127. if (options.data) {
  128. options.extraData = options.data;
  129. qx = $.param(options.data, traditional);
  130. }
  131. // give pre-submit callback an opportunity to abort the submit
  132. if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
  133. log('ajaxSubmit: submit aborted via beforeSubmit callback');
  134. return this;
  135. }
  136. // fire vetoable 'validate' event
  137. this.trigger('form-submit-validate', [a, this, options, veto]);
  138. if (veto.veto) {
  139. log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
  140. return this;
  141. }
  142. var q = $.param(a, traditional);
  143. if (qx) {
  144. q = ( q ? (q + '&' + qx) : qx );
  145. }
  146. if (options.type.toUpperCase() == 'GET') {
  147. options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
  148. options.data = null; // data is null for 'get'
  149. }
  150. else {
  151. options.data = q; // data is the query string for 'post'
  152. }
  153. var callbacks = [];
  154. if (options.resetForm) {
  155. callbacks.push(function() { $form.resetForm(); });
  156. }
  157. if (options.clearForm) {
  158. callbacks.push(function() { $form.clearForm(options.includeHidden); });
  159. }
  160. // perform a load on the target only if dataType is not provided
  161. if (!options.dataType && options.target) {
  162. var oldSuccess = options.success || function(){};
  163. callbacks.push(function(data) {
  164. var fn = options.replaceTarget ? 'replaceWith' : 'html';
  165. $(options.target)[fn](data).each(oldSuccess, arguments);
  166. });
  167. }
  168. else if (options.success) {
  169. callbacks.push(options.success);
  170. }
  171. options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
  172. var context = options.context || this ; // jQuery 1.4+ supports scope context
  173. for (var i=0, max=callbacks.length; i < max; i++) {
  174. callbacks[i].apply(context, [data, status, xhr || $form, $form]);
  175. }
  176. };
  177. if (options.error) {
  178. var oldError = options.error;
  179. options.error = function(xhr, status, error) {
  180. var context = options.context || this;
  181. oldError.apply(context, [xhr, status, error, $form]);
  182. };
  183. }
  184. if (options.complete) {
  185. var oldComplete = options.complete;
  186. options.complete = function(xhr, status) {
  187. var context = options.context || this;
  188. oldComplete.apply(context, [xhr, status, $form]);
  189. };
  190. }
  191. // are there files to upload?
  192. // [value] (issue #113), also see comment:
  193. // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219
  194. var fileInputs = $('input[type=file]:enabled', this).filter(function() { return $(this).val() !== ''; });
  195. var hasFileInputs = fileInputs.length > 0;
  196. var mp = 'multipart/form-data';
  197. var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);
  198. var fileAPI = feature.fileapi && feature.formdata;
  199. log("fileAPI :" + fileAPI);
  200. var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;
  201. var jqxhr;
  202. // options.iframe allows user to force iframe mode
  203. // 06-NOV-09: now defaulting to iframe mode if file input is detected
  204. if (options.iframe !== false && (options.iframe || shouldUseFrame)) {
  205. // hack to fix Safari hang (thanks to Tim Molendijk for this)
  206. // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
  207. if (options.closeKeepAlive) {
  208. $.get(options.closeKeepAlive, function() {
  209. jqxhr = fileUploadIframe(a);
  210. });
  211. }
  212. else {
  213. jqxhr = fileUploadIframe(a);
  214. }
  215. }
  216. else if ((hasFileInputs || multipart) && fileAPI) {
  217. jqxhr = fileUploadXhr(a);
  218. }
  219. else {
  220. jqxhr = $.ajax(options);
  221. }
  222. $form.removeData('jqxhr').data('jqxhr', jqxhr);
  223. // clear element array
  224. for (var k=0; k < elements.length; k++) {
  225. elements[k] = null;
  226. }
  227. // fire 'notify' event
  228. this.trigger('form-submit-notify', [this, options]);
  229. return this;
  230. // utility fn for deep serialization
  231. function deepSerialize(extraData){
  232. var serialized = $.param(extraData, options.traditional).split('&');
  233. var len = serialized.length;
  234. var result = [];
  235. var i, part;
  236. for (i=0; i < len; i++) {
  237. // #252; undo param space replacement
  238. serialized[i] = serialized[i].replace(/\+/g,' ');
  239. part = serialized[i].split('=');
  240. // #278; use array instead of object storage, favoring array serializations
  241. result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]);
  242. }
  243. return result;
  244. }
  245. // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)
  246. function fileUploadXhr(a) {
  247. var formdata = new FormData();
  248. for (var i=0; i < a.length; i++) {
  249. formdata.append(a[i].name, a[i].value);
  250. }
  251. if (options.extraData) {
  252. var serializedData = deepSerialize(options.extraData);
  253. for (i=0; i < serializedData.length; i++) {
  254. if (serializedData[i]) {
  255. formdata.append(serializedData[i][0], serializedData[i][1]);
  256. }
  257. }
  258. }
  259. options.data = null;
  260. var s = $.extend(true, {}, $.ajaxSettings, options, {
  261. contentType: false,
  262. processData: false,
  263. cache: false,
  264. type: method || 'POST'
  265. });
  266. if (options.uploadProgress) {
  267. // workaround because jqXHR does not expose upload property
  268. s.xhr = function() {
  269. var xhr = $.ajaxSettings.xhr();
  270. if (xhr.upload) {
  271. xhr.upload.addEventListener('progress', function(event) {
  272. var percent = 0;
  273. var position = event.loaded || event.position; /*event.position is deprecated*/
  274. var total = event.total;
  275. if (event.lengthComputable) {
  276. percent = Math.ceil(position / total * 100);
  277. }
  278. options.uploadProgress(event, position, total, percent);
  279. }, false);
  280. }
  281. return xhr;
  282. };
  283. }
  284. s.data = null;
  285. var beforeSend = s.beforeSend;
  286. s.beforeSend = function(xhr, o) {
  287. //Send FormData() provided by user
  288. if (options.formData) {
  289. o.data = options.formData;
  290. }
  291. else {
  292. o.data = formdata;
  293. }
  294. if(beforeSend) {
  295. beforeSend.call(this, xhr, o);
  296. }
  297. };
  298. return $.ajax(s);
  299. }
  300. // private function for handling file uploads (hat tip to YAHOO!)
  301. function fileUploadIframe(a) {
  302. var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle;
  303. var deferred = $.Deferred();
  304. // #341
  305. deferred.abort = function(status) {
  306. xhr.abort(status);
  307. };
  308. if (a) {
  309. // ensure that every serialized input is still enabled
  310. for (i=0; i < elements.length; i++) {
  311. el = $(elements[i]);
  312. if ( hasProp ) {
  313. el.prop('disabled', false);
  314. }
  315. else {
  316. el.removeAttr('disabled');
  317. }
  318. }
  319. }
  320. s = $.extend(true, {}, $.ajaxSettings, options);
  321. s.context = s.context || s;
  322. id = 'jqFormIO' + (new Date().getTime());
  323. if (s.iframeTarget) {
  324. $io = $(s.iframeTarget);
  325. n = $io.attr2('name');
  326. if (!n) {
  327. $io.attr2('name', id);
  328. }
  329. else {
  330. id = n;
  331. }
  332. }
  333. else {
  334. $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />');
  335. $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
  336. }
  337. io = $io[0];
  338. xhr = { // mock object
  339. aborted: 0,
  340. responseText: null,
  341. responseXML: null,
  342. status: 0,
  343. statusText: 'n/a',
  344. getAllResponseHeaders: function() {},
  345. getResponseHeader: function() {},
  346. setRequestHeader: function() {},
  347. abort: function(status) {
  348. var e = (status === 'timeout' ? 'timeout' : 'aborted');
  349. log('aborting upload... ' + e);
  350. this.aborted = 1;
  351. try { // #214, #257
  352. if (io.contentWindow.document.execCommand) {
  353. io.contentWindow.document.execCommand('Stop');
  354. }
  355. }
  356. catch(ignore) {}
  357. $io.attr('src', s.iframeSrc); // abort op in progress
  358. xhr.error = e;
  359. if (s.error) {
  360. s.error.call(s.context, xhr, e, status);
  361. }
  362. if (g) {
  363. $.event.trigger("ajaxError", [xhr, s, e]);
  364. }
  365. if (s.complete) {
  366. s.complete.call(s.context, xhr, e);
  367. }
  368. }
  369. };
  370. g = s.global;
  371. // trigger ajax global events so that activity/block indicators work like normal
  372. if (g && 0 === $.active++) {
  373. $.event.trigger("ajaxStart");
  374. }
  375. if (g) {
  376. $.event.trigger("ajaxSend", [xhr, s]);
  377. }
  378. if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {
  379. if (s.global) {
  380. $.active--;
  381. }
  382. deferred.reject();
  383. return deferred;
  384. }
  385. if (xhr.aborted) {
  386. deferred.reject();
  387. return deferred;
  388. }
  389. // add submitting element to data if we know it
  390. sub = form.clk;
  391. if (sub) {
  392. n = sub.name;
  393. if (n && !sub.disabled) {
  394. s.extraData = s.extraData || {};
  395. s.extraData[n] = sub.value;
  396. if (sub.type == "image") {
  397. s.extraData[n+'.x'] = form.clk_x;
  398. s.extraData[n+'.y'] = form.clk_y;
  399. }
  400. }
  401. }
  402. var CLIENT_TIMEOUT_ABORT = 1;
  403. var SERVER_ABORT = 2;
  404. function getDoc(frame) {
  405. /* it looks like contentWindow or contentDocument do not
  406. * carry the protocol property in ie8, when running under ssl
  407. * frame.document is the only valid response document, since
  408. * the protocol is know but not on the other two objects. strange?
  409. * "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy
  410. */
  411. var doc = null;
  412. // IE8 cascading access check
  413. try {
  414. if (frame.contentWindow) {
  415. doc = frame.contentWindow.document;
  416. }
  417. } catch(err) {
  418. // IE8 access denied under ssl & missing protocol
  419. log('cannot get iframe.contentWindow document: ' + err);
  420. }
  421. if (doc) { // successful getting content
  422. return doc;
  423. }
  424. try { // simply checking may throw in ie8 under ssl or mismatched protocol
  425. doc = frame.contentDocument ? frame.contentDocument : frame.document;
  426. } catch(err) {
  427. // last attempt
  428. log('cannot get iframe.contentDocument: ' + err);
  429. doc = frame.document;
  430. }
  431. return doc;
  432. }
  433. // Rails CSRF hack (thanks to Yvan Barthelemy)
  434. var csrf_token = $('meta[name=csrf-token]').attr('content');
  435. var csrf_param = $('meta[name=csrf-param]').attr('content');
  436. if (csrf_param && csrf_token) {
  437. s.extraData = s.extraData || {};
  438. s.extraData[csrf_param] = csrf_token;
  439. }
  440. // take a breath so that pending repaints get some cpu time before the upload starts
  441. function doSubmit() {
  442. // make sure form attrs are set
  443. var t = $form.attr2('target'),
  444. a = $form.attr2('action'),
  445. mp = 'multipart/form-data',
  446. et = $form.attr('enctype') || $form.attr('encoding') || mp;
  447. // update form attrs in IE friendly way
  448. form.setAttribute('target',id);
  449. if (!method || /post/i.test(method) ) {
  450. form.setAttribute('method', 'POST');
  451. }
  452. if (a != s.url) {
  453. form.setAttribute('action', s.url);
  454. }
  455. // ie borks in some cases when setting encoding
  456. if (! s.skipEncodingOverride && (!method || /post/i.test(method))) {
  457. $form.attr({
  458. encoding: 'multipart/form-data',
  459. enctype: 'multipart/form-data'
  460. });
  461. }
  462. // support timout
  463. if (s.timeout) {
  464. timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout);
  465. }
  466. // look for server aborts
  467. function checkState() {
  468. try {
  469. var state = getDoc(io).readyState;
  470. log('state = ' + state);
  471. if (state && state.toLowerCase() == 'uninitialized') {
  472. setTimeout(checkState,50);
  473. }
  474. }
  475. catch(e) {
  476. log('Server abort: ' , e, ' (', e.name, ')');
  477. cb(SERVER_ABORT);
  478. if (timeoutHandle) {
  479. clearTimeout(timeoutHandle);
  480. }
  481. timeoutHandle = undefined;
  482. }
  483. }
  484. // add "extra" data to form if provided in options
  485. var extraInputs = [];
  486. try {
  487. if (s.extraData) {
  488. for (var n in s.extraData) {
  489. if (s.extraData.hasOwnProperty(n)) {
  490. // if using the $.param format that allows for multiple values with the same name
  491. if($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) {
  492. extraInputs.push(
  493. $('<input type="hidden" name="'+s.extraData[n].name+'">').val(s.extraData[n].value)
  494. .appendTo(form)[0]);
  495. } else {
  496. extraInputs.push(
  497. $('<input type="hidden" name="'+n+'">').val(s.extraData[n])
  498. .appendTo(form)[0]);
  499. }
  500. }
  501. }
  502. }
  503. if (!s.iframeTarget) {
  504. // add iframe to doc and submit the form
  505. $io.appendTo('body');
  506. }
  507. if (io.attachEvent) {
  508. io.attachEvent('onload', cb);
  509. }
  510. else {
  511. io.addEventListener('load', cb, false);
  512. }
  513. setTimeout(checkState,15);
  514. try {
  515. form.submit();
  516. } catch(err) {
  517. // just in case form has element with name/id of 'submit'
  518. var submitFn = document.createElement('form').submit;
  519. submitFn.apply(form);
  520. }
  521. }
  522. finally {
  523. // reset attrs and remove "extra" input elements
  524. form.setAttribute('action',a);
  525. form.setAttribute('enctype', et); // #380
  526. if(t) {
  527. form.setAttribute('target', t);
  528. } else {
  529. $form.removeAttr('target');
  530. }
  531. $(extraInputs).remove();
  532. }
  533. }
  534. if (s.forceSync) {
  535. doSubmit();
  536. }
  537. else {
  538. setTimeout(doSubmit, 10); // this lets dom updates render
  539. }
  540. var data, doc, domCheckCount = 50, callbackProcessed;
  541. function cb(e) {
  542. if (xhr.aborted || callbackProcessed) {
  543. return;
  544. }
  545. doc = getDoc(io);
  546. if(!doc) {
  547. log('cannot access response document');
  548. e = SERVER_ABORT;
  549. }
  550. if (e === CLIENT_TIMEOUT_ABORT && xhr) {
  551. xhr.abort('timeout');
  552. deferred.reject(xhr, 'timeout');
  553. return;
  554. }
  555. else if (e == SERVER_ABORT && xhr) {
  556. xhr.abort('server abort');
  557. deferred.reject(xhr, 'error', 'server abort');
  558. return;
  559. }
  560. if (!doc || doc.location.href == s.iframeSrc) {
  561. // response not received yet
  562. if (!timedOut) {
  563. return;
  564. }
  565. }
  566. if (io.detachEvent) {
  567. io.detachEvent('onload', cb);
  568. }
  569. else {
  570. io.removeEventListener('load', cb, false);
  571. }
  572. var status = 'success', errMsg;
  573. try {
  574. if (timedOut) {
  575. throw 'timeout';
  576. }
  577. var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
  578. log('isXml='+isXml);
  579. if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) {
  580. if (--domCheckCount) {
  581. // in some browsers (Opera) the iframe DOM is not always traversable when
  582. // the onload callback fires, so we loop a bit to accommodate
  583. log('requeing onLoad callback, DOM not available');
  584. setTimeout(cb, 250);
  585. return;
  586. }
  587. // let this fall through because server response could be an empty document
  588. //log('Could not access iframe DOM after mutiple tries.');
  589. //throw 'DOMException: not available';
  590. }
  591. //log('response detected');
  592. var docRoot = doc.body ? doc.body : doc.documentElement;
  593. xhr.responseText = docRoot ? docRoot.innerHTML : null;
  594. xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
  595. if (isXml) {
  596. s.dataType = 'xml';
  597. }
  598. xhr.getResponseHeader = function(header){
  599. var headers = {'content-type': s.dataType};
  600. return headers[header.toLowerCase()];
  601. };
  602. // support for XHR 'status' & 'statusText' emulation :
  603. if (docRoot) {
  604. xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status;
  605. xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText;
  606. }
  607. var dt = (s.dataType || '').toLowerCase();
  608. var scr = /(json|script|text)/.test(dt);
  609. if (scr || s.textarea) {
  610. // see if user embedded response in textarea
  611. var ta = doc.getElementsByTagName('textarea')[0];
  612. if (ta) {
  613. xhr.responseText = ta.value;
  614. // support for XHR 'status' & 'statusText' emulation :
  615. xhr.status = Number( ta.getAttribute('status') ) || xhr.status;
  616. xhr.statusText = ta.getAttribute('statusText') || xhr.statusText;
  617. }
  618. else if (scr) {
  619. // account for browsers injecting pre around json response
  620. var pre = doc.getElementsByTagName('pre')[0];
  621. var b = doc.getElementsByTagName('body')[0];
  622. if (pre) {
  623. xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;
  624. }
  625. else if (b) {
  626. xhr.responseText = b.textContent ? b.textContent : b.innerText;
  627. }
  628. }
  629. }
  630. else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) {
  631. xhr.responseXML = toXml(xhr.responseText);
  632. }
  633. try {
  634. data = httpData(xhr, dt, s);
  635. }
  636. catch (err) {
  637. status = 'parsererror';
  638. xhr.error = errMsg = (err || status);
  639. }
  640. }
  641. catch (err) {
  642. log('error caught: ',err);
  643. status = 'error';
  644. xhr.error = errMsg = (err || status);
  645. }
  646. if (xhr.aborted) {
  647. log('upload aborted');
  648. status = null;
  649. }
  650. if (xhr.status) { // we've set xhr.status
  651. status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error';
  652. }
  653. // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
  654. if (status === 'success') {
  655. if (s.success) {
  656. s.success.call(s.context, data, 'success', xhr);
  657. }
  658. deferred.resolve(xhr.responseText, 'success', xhr);
  659. if (g) {
  660. $.event.trigger("ajaxSuccess", [xhr, s]);
  661. }
  662. }
  663. else if (status) {
  664. if (errMsg === undefined) {
  665. errMsg = xhr.statusText;
  666. }
  667. if (s.error) {
  668. s.error.call(s.context, xhr, status, errMsg);
  669. }
  670. deferred.reject(xhr, 'error', errMsg);
  671. if (g) {
  672. $.event.trigger("ajaxError", [xhr, s, errMsg]);
  673. }
  674. }
  675. if (g) {
  676. $.event.trigger("ajaxComplete", [xhr, s]);
  677. }
  678. if (g && ! --$.active) {
  679. $.event.trigger("ajaxStop");
  680. }
  681. if (s.complete) {
  682. s.complete.call(s.context, xhr, status);
  683. }
  684. callbackProcessed = true;
  685. if (s.timeout) {
  686. clearTimeout(timeoutHandle);
  687. }
  688. // clean up
  689. setTimeout(function() {
  690. if (!s.iframeTarget) {
  691. $io.remove();
  692. }
  693. else { //adding else to clean up existing iframe response.
  694. $io.attr('src', s.iframeSrc);
  695. }
  696. xhr.responseXML = null;
  697. }, 100);
  698. }
  699. var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+)
  700. if (window.ActiveXObject) {
  701. doc = new ActiveXObject('Microsoft.XMLDOM');
  702. doc.async = 'false';
  703. doc.loadXML(s);
  704. }
  705. else {
  706. doc = (new DOMParser()).parseFromString(s, 'text/xml');
  707. }
  708. return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null;
  709. };
  710. var parseJSON = $.parseJSON || function(s) {
  711. /*jslint evil:true */
  712. return window['eval']('(' + s + ')');
  713. };
  714. var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4
  715. var ct = xhr.getResponseHeader('content-type') || '',
  716. xml = type === 'xml' || !type && ct.indexOf('xml') >= 0,
  717. data = xml ? xhr.responseXML : xhr.responseText;
  718. if (xml && data.documentElement.nodeName === 'parsererror') {
  719. if ($.error) {
  720. $.error('parsererror');
  721. }
  722. }
  723. if (s && s.dataFilter) {
  724. data = s.dataFilter(data, type);
  725. }
  726. if (typeof data === 'string') {
  727. if (type === 'json' || !type && ct.indexOf('json') >= 0) {
  728. data = parseJSON(data);
  729. } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) {
  730. $.globalEval(data);
  731. }
  732. }
  733. return data;
  734. };
  735. return deferred;
  736. }
  737. };
  738. /**
  739. * ajaxForm() provides a mechanism for fully automating form submission.
  740. *
  741. * The advantages of using this method instead of ajaxSubmit() are:
  742. *
  743. * 1: This method will include coordinates for <input type="image" /> elements (if the element
  744. * is used to submit the form).
  745. * 2. This method will include the submit element's name/value data (for the element that was
  746. * used to submit the form).
  747. * 3. This method binds the submit() method to the form for you.
  748. *
  749. * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
  750. * passes the options argument along after properly binding events for submit elements and
  751. * the form itself.
  752. */
  753. $.fn.ajaxForm = function(options) {
  754. options = options || {};
  755. options.delegation = options.delegation && $.isFunction($.fn.on);
  756. // in jQuery 1.3+ we can fix mistakes with the ready state
  757. if (!options.delegation && this.length === 0) {
  758. var o = { s: this.selector, c: this.context };
  759. if (!$.isReady && o.s) {
  760. log('DOM not ready, queuing ajaxForm');
  761. $(function() {
  762. $(o.s,o.c).ajaxForm(options);
  763. });
  764. return this;
  765. }
  766. // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
  767. log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)'));
  768. return this;
  769. }
  770. if ( options.delegation ) {
  771. $(document)
  772. .off('submit.form-plugin', this.selector, doAjaxSubmit)
  773. .off('click.form-plugin', this.selector, captureSubmittingElement)
  774. .on('submit.form-plugin', this.selector, options, doAjaxSubmit)
  775. .on('click.form-plugin', this.selector, options, captureSubmittingElement);
  776. return this;
  777. }
  778. return this.ajaxFormUnbind()
  779. .bind('submit.form-plugin', options, doAjaxSubmit)
  780. .bind('click.form-plugin', options, captureSubmittingElement);
  781. };
  782. // private event handlers
  783. function doAjaxSubmit(e) {
  784. /*jshint validthis:true */
  785. var options = e.data;
  786. if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed
  787. e.preventDefault();
  788. $(e.target).ajaxSubmit(options); // #365
  789. }
  790. }
  791. function captureSubmittingElement(e) {
  792. /*jshint validthis:true */
  793. var target = e.target;
  794. var $el = $(target);
  795. if (!($el.is("[type=submit],[type=image]"))) {
  796. // is this a child element of the submit el? (ex: a span within a button)
  797. var t = $el.closest('[type=submit]');
  798. if (t.length === 0) {
  799. return;
  800. }
  801. target = t[0];
  802. }
  803. var form = this;
  804. form.clk = target;
  805. if (target.type == 'image') {
  806. if (e.offsetX !== undefined) {
  807. form.clk_x = e.offsetX;
  808. form.clk_y = e.offsetY;
  809. } else if (typeof $.fn.offset == 'function') {
  810. var offset = $el.offset();
  811. form.clk_x = e.pageX - offset.left;
  812. form.clk_y = e.pageY - offset.top;
  813. } else {
  814. form.clk_x = e.pageX - target.offsetLeft;
  815. form.clk_y = e.pageY - target.offsetTop;
  816. }
  817. }
  818. // clear form vars
  819. setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
  820. }
  821. // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
  822. $.fn.ajaxFormUnbind = function() {
  823. return this.unbind('submit.form-plugin click.form-plugin');
  824. };
  825. /**
  826. * formToArray() gathers form element data into an array of objects that can
  827. * be passed to any of the following ajax functions: $.get, $.post, or load.
  828. * Each object in the array has both a 'name' and 'value' property. An example of
  829. * an array for a simple login form might be:
  830. *
  831. * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
  832. *
  833. * It is this array that is passed to pre-submit callback functions provided to the
  834. * ajaxSubmit() and ajaxForm() methods.
  835. */
  836. $.fn.formToArray = function(semantic, elements) {
  837. var a = [];
  838. if (this.length === 0) {
  839. return a;
  840. }
  841. var form = this[0];
  842. var formId = this.attr('id');
  843. var els = semantic ? form.getElementsByTagName('*') : form.elements;
  844. var els2;
  845. if (els && !/MSIE [678]/.test(navigator.userAgent)) { // #390
  846. els = $(els).get(); // convert to standard array
  847. }
  848. // #386; account for inputs outside the form which use the 'form' attribute
  849. if ( formId ) {
  850. els2 = $(':input[form="' + formId + '"]').get(); // hat tip @thet
  851. if ( els2.length ) {
  852. els = (els || []).concat(els2);
  853. }
  854. }
  855. if (!els || !els.length) {
  856. return a;
  857. }
  858. var i,j,n,v,el,max,jmax;
  859. for(i=0, max=els.length; i < max; i++) {
  860. el = els[i];
  861. n = el.name;
  862. if (!n || el.disabled) {
  863. continue;
  864. }
  865. if (semantic && form.clk && el.type == "image") {
  866. // handle image inputs on the fly when semantic == true
  867. if(form.clk == el) {
  868. a.push({name: n, value: $(el).val(), type: el.type });
  869. a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
  870. }
  871. continue;
  872. }
  873. v = $.fieldValue(el, true);
  874. if (v && v.constructor == Array) {
  875. if (elements) {
  876. elements.push(el);
  877. }
  878. for(j=0, jmax=v.length; j < jmax; j++) {
  879. a.push({name: n, value: v[j]});
  880. }
  881. }
  882. else if (feature.fileapi && el.type == 'file') {
  883. if (elements) {
  884. elements.push(el);
  885. }
  886. var files = el.files;
  887. if (files.length) {
  888. for (j=0; j < files.length; j++) {
  889. a.push({name: n, value: files[j], type: el.type});
  890. }
  891. }
  892. else {
  893. // #180
  894. a.push({ name: n, value: '', type: el.type });
  895. }
  896. }
  897. else if (v !== null && typeof v != 'undefined') {
  898. if (elements) {
  899. elements.push(el);
  900. }
  901. a.push({name: n, value: v, type: el.type, required: el.required});
  902. }
  903. }
  904. if (!semantic && form.clk) {
  905. // input type=='image' are not found in elements array! handle it here
  906. var $input = $(form.clk), input = $input[0];
  907. n = input.name;
  908. if (n && !input.disabled && input.type == 'image') {
  909. a.push({name: n, value: $input.val()});
  910. a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
  911. }
  912. }
  913. return a;
  914. };
  915. /**
  916. * Serializes form data into a 'submittable' string. This method will return a string
  917. * in the format: name1=value1&amp;name2=value2
  918. */
  919. $.fn.formSerialize = function(semantic) {
  920. //hand off to jQuery.param for proper encoding
  921. return $.param(this.formToArray(semantic));
  922. };
  923. /**
  924. * Serializes all field elements in the jQuery object into a query string.
  925. * This method will return a string in the format: name1=value1&amp;name2=value2
  926. */
  927. $.fn.fieldSerialize = function(successful) {
  928. var a = [];
  929. this.each(function() {
  930. var n = this.name;
  931. if (!n) {
  932. return;
  933. }
  934. var v = $.fieldValue(this, successful);
  935. if (v && v.constructor == Array) {
  936. for (var i=0,max=v.length; i < max; i++) {
  937. a.push({name: n, value: v[i]});
  938. }
  939. }
  940. else if (v !== null && typeof v != 'undefined') {
  941. a.push({name: this.name, value: v});
  942. }
  943. });
  944. //hand off to jQuery.param for proper encoding
  945. return $.param(a);
  946. };
  947. /**
  948. * Returns the value(s) of the element in the matched set. For example, consider the following form:
  949. *
  950. * <form><fieldset>
  951. * <input name="A" type="text" />
  952. * <input name="A" type="text" />
  953. * <input name="B" type="checkbox" value="B1" />
  954. * <input name="B" type="checkbox" value="B2"/>
  955. * <input name="C" type="radio" value="C1" />
  956. * <input name="C" type="radio" value="C2" />
  957. * </fieldset></form>
  958. *
  959. * var v = $('input[type=text]').fieldValue();
  960. * // if no values are entered into the text inputs
  961. * v == ['','']
  962. * // if values entered into the text inputs are 'foo' and 'bar'
  963. * v == ['foo','bar']
  964. *
  965. * var v = $('input[type=checkbox]').fieldValue();
  966. * // if neither checkbox is checked
  967. * v === undefined
  968. * // if both checkboxes are checked
  969. * v == ['B1', 'B2']
  970. *
  971. * var v = $('input[type=radio]').fieldValue();
  972. * // if neither radio is checked
  973. * v === undefined
  974. * // if first radio is checked
  975. * v == ['C1']
  976. *
  977. * The successful argument controls whether or not the field element must be 'successful'
  978. * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
  979. * The default value of the successful argument is true. If this value is false the value(s)
  980. * for each element is returned.
  981. *
  982. * Note: This method *always* returns an array. If no valid value can be determined the
  983. * array will be empty, otherwise it will contain one or more values.
  984. */
  985. $.fn.fieldValue = function(successful) {
  986. for (var val=[], i=0, max=this.length; i < max; i++) {
  987. var el = this[i];
  988. var v = $.fieldValue(el, successful);
  989. if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) {
  990. continue;
  991. }
  992. if (v.constructor == Array) {
  993. $.merge(val, v);
  994. }
  995. else {
  996. val.push(v);
  997. }
  998. }
  999. return val;
  1000. };
  1001. /**
  1002. * Returns the value of the field element.
  1003. */
  1004. $.fieldValue = function(el, successful) {
  1005. var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
  1006. if (successful === undefined) {
  1007. successful = true;
  1008. }
  1009. if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
  1010. (t == 'checkbox' || t == 'radio') && !el.checked ||
  1011. (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
  1012. tag == 'select' && el.selectedIndex == -1)) {
  1013. return null;
  1014. }
  1015. if (tag == 'select') {
  1016. var index = el.selectedIndex;
  1017. if (index < 0) {
  1018. return null;
  1019. }
  1020. var a = [], ops = el.options;
  1021. var one = (t == 'select-one');
  1022. var max = (one ? index+1 : ops.length);
  1023. for(var i=(one ? index : 0); i < max; i++) {
  1024. var op = ops[i];
  1025. if (op.selected) {
  1026. var v = op.value;
  1027. if (!v) { // extra pain for IE...
  1028. v = (op.attributes && op.attributes.value && !(op.attributes.value.specified)) ? op.text : op.value;
  1029. }
  1030. if (one) {
  1031. return v;
  1032. }
  1033. a.push(v);
  1034. }
  1035. }
  1036. return a;
  1037. }
  1038. return $(el).val();
  1039. };
  1040. /**
  1041. * Clears the form data. Takes the following actions on the form's input fields:
  1042. * - input text fields will have their 'value' property set to the empty string
  1043. * - select elements will have their 'selectedIndex' property set to -1
  1044. * - checkbox and radio inputs will have their 'checked' property set to false
  1045. * - inputs of type submit, button, reset, and hidden will *not* be effected
  1046. * - button elements will *not* be effected
  1047. */
  1048. $.fn.clearForm = function(includeHidden) {
  1049. return this.each(function() {
  1050. $('input,select,textarea', this).clearFields(includeHidden);
  1051. });
  1052. };
  1053. /**
  1054. * Clears the selected form elements.
  1055. */
  1056. $.fn.clearFields = $.fn.clearInputs = function(includeHidden) {
  1057. var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list
  1058. return this.each(function() {
  1059. var t = this.type, tag = this.tagName.toLowerCase();
  1060. if (re.test(t) || tag == 'textarea') {
  1061. this.value = '';
  1062. }
  1063. else if (t == 'checkbox' || t == 'radio') {
  1064. this.checked = false;
  1065. }
  1066. else if (tag == 'select') {
  1067. this.selectedIndex = -1;
  1068. }
  1069. else if (t == "file") {
  1070. if (/MSIE/.test(navigator.userAgent)) {
  1071. $(this).replaceWith($(this).clone(true));
  1072. } else {
  1073. $(this).val('');
  1074. }
  1075. }
  1076. else if (includeHidden) {
  1077. // includeHidden can be the value true, or it can be a selector string
  1078. // indicating a special test; for example:
  1079. // $('#myForm').clearForm('.special:hidden')
  1080. // the above would clean hidden inputs that have the class of 'special'
  1081. if ( (includeHidden === true && /hidden/.test(t)) ||
  1082. (typeof includeHidden == 'string' && $(this).is(includeHidden)) ) {
  1083. this.value = '';
  1084. }
  1085. }
  1086. });
  1087. };
  1088. /**
  1089. * Resets the form data. Causes all form elements to be reset to their original value.
  1090. */
  1091. $.fn.resetForm = function() {
  1092. return this.each(function() {
  1093. // guard against an input with the name of 'reset'
  1094. // note that IE reports the reset function as an 'object'
  1095. if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) {
  1096. this.reset();
  1097. }
  1098. });
  1099. };
  1100. /**
  1101. * Enables or disables any matching elements.
  1102. */
  1103. $.fn.enable = function(b) {
  1104. if (b === undefined) {
  1105. b = true;
  1106. }
  1107. return this.each(function() {
  1108. this.disabled = !b;
  1109. });
  1110. };
  1111. /**
  1112. * Checks/unchecks any matching checkboxes or radio buttons and
  1113. * selects/deselects and matching option elements.
  1114. */
  1115. $.fn.selected = function(select) {
  1116. if (select === undefined) {
  1117. select = true;
  1118. }
  1119. return this.each(function() {
  1120. var t = this.type;
  1121. if (t == 'checkbox' || t == 'radio') {
  1122. this.checked = select;
  1123. }
  1124. else if (this.tagName.toLowerCase() == 'option') {
  1125. var $sel = $(this).parent('select');
  1126. if (select && $sel[0] && $sel[0].type == 'select-one') {
  1127. // deselect all other options
  1128. $sel.find('option').selected(false);
  1129. }
  1130. this.selected = select;
  1131. }
  1132. });
  1133. };
  1134. // expose debug var
  1135. $.fn.ajaxSubmit.debug = false;
  1136. // helper fn for console logging
  1137. function log() {
  1138. if (!$.fn.ajaxSubmit.debug) {
  1139. return;
  1140. }
  1141. var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
  1142. if (window.console && window.console.log) {
  1143. window.console.log(msg);
  1144. }
  1145. else if (window.opera && window.opera.postError) {
  1146. window.opera.postError(msg);
  1147. }
  1148. }
  1149. }));