PageRenderTime 74ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/files/jquery.form/3.46/jquery.form.js

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