jquery.form.js 38 KB

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