jquery.form.js 40 KB

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