ajaxForm.js 37 KB

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