1
0

jquery.form.js 41 KB

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