jquery.form.js 39 KB

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