jquery.form.js 37 KB

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