jquery.form.js 38 KB

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