PageRenderTime 50ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/files/wordpress/3.8/js/jquery/jquery.form.js

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