jquery.form.js 40KB

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