jquery.form.js 41 KB

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