UNPKG

jquery-form-plus

Version:

The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX.

24 lines (20 loc) 17.1 kB
/*! * jQuery Form Plugin * version: 4.3.0 * Requires jQuery v1.7.2 or later * Project repository: https://github.com/brettz9/jquery-form-plus * Copyright 2017 Kevin Morris * Copyright 2006 M. Alsup * Dual licensed under the LGPL-2.1+ or MIT licenses * https://github.com/brettz9/jquery-form-plus#license * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ !function(r){"function"==typeof define&&define.amd?define(["jquery"],r):"object"==typeof module&&module.exports?module.exports=function(e,t){return void 0===t&&(t="undefined"==typeof window?require("jquery")(e):require("jquery")),r(t,e),t}:r(jQuery)}(function(L,e){"use strict";const u=/\r?\n/g,M="multipart/form-data",O=function(e,t){return{}.hasOwnProperty.call(e,t)},X=e||window,g=e&&e.navigator||navigator,v={};v.fileapi=void 0!==L('<input type="file">').get(0).files,v.formdata=void 0!==X.FormData;const C=!!L.fn.prop;function s(e){var t=e.data;e.isDefaultPrevented()||(e.preventDefault(),L(e.target).closest("form").ajaxSubmit(t))}function i(e){let{target:t}=e;const r=L(t);if(!r.is("[type=submit],[type=image]")){var a=r.closest("[type=submit]");if(0===a.length)return;t=a[0]}const n=t.form;n.clk=t,"image"===t.type&&(void 0!==e.offsetX?(n.clk_x=e.offsetX,n.clk_y=e.offsetY):"function"==typeof L.fn.offset?(a=r.offset(),n.clk_x=e.pageX-a.left,n.clk_y=e.pageY-a.top):(n.clk_x=e.pageX-t.offsetLeft,n.clk_y=e.pageY-t.offsetTop));setTimeout(function(){n.clk=null,n.clk_x=null,n.clk_y=null},100)}function q(){var e;L.fn.ajaxSubmit.debug&&(e="[jquery.form] "+Array.prototype.join.call(arguments,""),X.console&&X.console.log?X.console.log(e):X.opera&&X.opera.postError&&X.opera.postError(e))}L.fn.attr2=function(){if(!C)return this.attr.apply(this,arguments);var e=this.prop.apply(this,arguments);return e&&e.jquery||"string"==typeof e?e:this.attr.apply(this,arguments)},L.fn.ajaxSubmit=function(f,e,t,r){if(!this.length)return q("ajaxSubmit: skipping submit process - no element selected"),this;const w=this;"function"==typeof f?f={success:f}:"string"==typeof f||!1===f&&0<arguments.length?(f={data:e,dataType:t,url:f},"function"==typeof r&&(f.success=r)):void 0===f&&(f={});const E=f.method||f.type||this.attr2("method");t=f.url||this.attr2("action");let a="string"==typeof t?L.trim(t):"";a=a||X.location.href||"",a=a&&(a.match(/^([^#]+)/)||[])[1];r=/(MSIE|Trident)/.test(g.userAgent||"")&&/^https/i.test(X.location.href||"")?"javascript:false":"about:blank";f=L.extend(!0,{iframeSrc:r,success:L.ajaxSettings.success,type:E||L.ajaxSettings.type,url:a},f);t={};if(this.trigger("form-pre-serialize",[this,f,t]),t.veto)return q("ajaxSubmit: submit vetoed via form-pre-serialize trigger"),this;if(f.beforeSerialize&&!1===f.beforeSerialize(this,f))return q("ajaxSubmit: submit aborted via beforeSerialize callback"),this;var{traditional:r=L.ajaxSettings.traditional}=f;const o=[],n=this.formToArray(f.semantic,o,f.filtering);let s;if(f.data&&(l=L.isFunction(f.data)?f.data(n):f.data,f.extraData=l,s=L.param(l,r)),f.beforeSubmit&&!1===f.beforeSubmit(n,this,f))return q("ajaxSubmit: submit aborted via beforeSubmit callback"),this;if(this.trigger("form-submit-validate",[n,this,f,t]),t.veto)return q("ajaxSubmit: submit vetoed via form-submit-validate trigger"),this;let i=L.param(n,r);s&&(i=i?i+"&"+s:s),"GET"===f.type.toUpperCase()?(f.url+=(0<=f.url.indexOf("?")?"&":"?")+i,f.data=null):f.data=i;const c=[];if(f.resetForm&&c.push(function(){w.resetForm()}),f.clearForm&&c.push(function(){w.clearForm(f.includeHidden)}),!f.dataType&&f.target){const m=f.success||function(){};c.push(function(e,t,r){const a=f.replaceTarget?"replaceWith":"html",n=arguments;e=L.parseHTML(L("<div>").text(e).html()),L(f.target)[a](e).each(function(){m.apply(this,n)})})}else f.success&&(L.isArray(f.success)?L.merge(c,f.success):c.push(f.success));if(f.success=function(e,t,r){var a=f.context||this;for(const n of c)n.apply(a,[e,t,r||w,w])},f.error){const d=f.error;f.error=function(e,t,r){var a=f.context||this;d.apply(a,[e,t,r,w])}}if(f.complete){const h=f.complete;f.complete=function(e,t){var r=f.context||this;h.apply(r,[e,t,w])}}var l=0<L("input[type=file]:enabled",this).filter(function(){return""!==L(this).val()}).length,t=w.attr("enctype")===M||w.attr("encoding")===M,r=v.fileapi&&v.formdata;q("fileAPI :"+r);let u;!1!==f.iframe&&(f.iframe||(l||t)&&!r)?f.closeKeepAlive?L.get(f.closeKeepAlive,function(){u=p(n)}):u=p(n):u=(l||t)&&r?function(e){const r=new FormData;for(var{name:t,value:a}of e)r.append(t,a);if(f.extraData)for(const s of function(e){const t=L.param(e,f.traditional).split("&"),r=[];for(const n of t){var a=n.replace(/\+/g," ").split("=");r.push([decodeURIComponent(a[0]),decodeURIComponent(a[1])])}return r}(f.extraData))s&&r.append(s[0],s[1]);f.data=null;const n=L.extend(!0,{},L.ajaxSettings,f,{cache:!1,contentType:!1,processData:!1,type:E||"POST"});f.uploadProgress&&(n.xhr=function(){const e=L.ajaxSettings.xhr();return e.upload&&e.upload.addEventListener("progress",function(e){let t=0;var r=e.loaded||e.position,a=e.total;e.lengthComputable&&(t=Math.ceil(r/a*100)),f.uploadProgress(e,r,a,t)},!1),e});n.data=null;const o=n.beforeSend;return n.beforeSend=function(e,t){f.formData?t.data=f.formData:t.data=r,o&&o.call(this,e,t)},L.ajax(n)}(n):L.ajax(f),w.removeData("jqxhr").data("jqxhr",u);for(let e=0;e<o.length;e++)o[e]=null;return this.trigger("form-submit-notify",[this,f]),this;function p(e){const s=w[0];if(e)for(const a of o){const n=L(a);C?n.prop("disabled",!1):n.removeAttr("disabled")}const p=L.extend(!0,{},L.ajaxSettings,f);p.context=p.context||p;let i="jqFormIO"+(new Date).getTime();const c=s.ownerDocument,l=w.closest("body");let m;if(p.iframeTarget){m=L(p.iframeTarget,c);const name=m.attr2("name");name?i=name:m.attr2("name",i)}else m=L('<iframe name="'+i+'" src="'+p.iframeSrc+'" />',c),m.css({left:"-1000px",position:"absolute",top:"-1000px"});const d=m[0],h=p.global,g={abort:function(e){var t="timeout"===e?"timeout":"aborted";q("aborting upload... "+t),this.aborted=1;try{d.contentWindow.document.execCommand&&d.contentWindow.document.execCommand("Stop")}catch(e){}m.attr("src",p.iframeSrc),g.error=t,p.error&&p.error.call(p.context,g,t,e),h&&L.event.trigger("ajaxError",[g,p,t]),p.complete&&p.complete.call(p.context,g,t)},aborted:0,getAllResponseHeaders:function(){},getResponseHeader:function(){},responseText:null,responseXML:null,setRequestHeader:function(){},status:0,statusText:"n/a"};h&&0==L.active++&&L.event.trigger("ajaxStart"),h&&L.event.trigger("ajaxSend",[g,p]);const v=L.Deferred();if(v.abort=function(e){g.abort(e)},p.beforeSend&&!1===p.beforeSend.call(p.context,g,p))return p.global&&L.active--,v.reject(),v;if(g.aborted)return v.reject(),v;var t=s.clk;if(t){const{name}=t;name&&!t.disabled&&(p.extraData=p.extraData||{},p.extraData[name]=t.value,"image"===t.type&&(p.extraData[name+".x"]=s.clk_x,p.extraData[name+".y"]=s.clk_y))}const x=1,y=2;function b(t){let r=null;try{t.contentWindow&&(r=t.contentWindow.document)}catch(e){q("cannot get iframe.contentWindow document: "+e)}if(r)return r;try{r=t.contentDocument||t.document}catch(e){q("cannot get iframe.contentDocument: "+e),r=t.document}return r}e=L("meta[name=csrf-token]").attr("content"),t=L("meta[name=csrf-param]").attr("content");t&&e&&(p.extraData=p.extraData||{},p.extraData[t]=e);let T,j;function r(){var e=w.attr2("action"),t=w.attr("enctype")||w.attr("encoding")||M,r=w.attr2("target");s.setAttribute("target",i),E&&!/post/i.test(E)||s.setAttribute("method","POST"),e!==p.url&&s.setAttribute("action",p.url),p.skipEncodingOverride||E&&!/post/i.test(E)||w.attr({encoding:"multipart/form-data",enctype:"multipart/form-data"}),p.timeout&&(j=setTimeout(function(){T=!0,F(x)},p.timeout));const a=[];try{if(p.extraData)for(const n of Object.values(p.extraData))L.isPlainObject(n)&&O(n,"name")&&O(n,"value")?a.push(L('<input type="hidden" name="'+n.name+'">',c).val(n.value).appendTo(s)[0]):a.push(L('<input type="hidden" name="'+name+'">',c).val(n).appendTo(s)[0]);p.iframeTarget||m.appendTo(l),d.attachEvent?d.attachEvent("onload",F):d.addEventListener("load",F,!1);setTimeout(function e(){try{const t=b(d).readyState;q("state = "+t),t&&"uninitialized"===t.toLowerCase()&&setTimeout(e,50)}catch(e){q("Server abort: ",e," (",e.name,")"),F(y),j&&clearTimeout(j),j=void 0}},15);try{s.submit()}catch(e){const o=document.createElement("form").submit;o.apply(s)}}finally{s.setAttribute("action",e),s.setAttribute("enctype",t),r?s.setAttribute("target",r):w.removeAttr("target"),L(a).remove()}}p.forceSync?r():setTimeout(r,10);const S=L.parseXML||function(e,t){return X.ActiveXObject?((t=new ActiveXObject("Microsoft.XMLDOM")).async="false",t.loadXML(e)):t=(new DOMParser).parseFromString(e,"text/xml"),t&&t.documentElement&&"parsererror"!==t.documentElement.nodeName?t:null};let k,A,D=50;function F(e){if(!g.aborted&&!A){const c=b(d);if(c||(q("cannot access response document"),e=y),e===x&&g)return g.abort("timeout"),void v.reject(g,"timeout");if(e===y&&g)return g.abort("server abort"),void v.reject(g,"error","server abort");if(c&&c.location.href!==p.iframeSrc||T){d.detachEvent?d.detachEvent("onload",F):d.removeEventListener("load",F,!1);let e,t,r="success";try{if(T)throw new Error("timeout");var a="xml"===p.dataType||c.XMLDocument||L.isXMLDoc(c);if(q("isXml="+a),!a&&X.opera&&(null===c.body||!c.body.innerHTML)&&--D){q("requeing onLoad callback, DOM not available");const l=250;return void setTimeout(F,250)}const u=c.body||c.documentElement;g.responseText=u?u.innerHTML:null,g.responseXML=c.XMLDocument||c,a&&(p.dataType="xml"),g.getResponseHeader=function(e){return{"content-type":p.dataType}[e.toLowerCase()]},u&&(g.status=Number(u.getAttribute("status"))||g.status,g.statusText=u.getAttribute("statusText")||g.statusText);var n,o,s=(p.dataType||"").toLowerCase(),i=/(json|script|text)/.test(s);if(i||p.textarea){const f=c.getElementsByTagName("textarea")[0];f?(g.responseText=f.value,g.status=Number(f.getAttribute("status"))||g.status,g.statusText=f.getAttribute("statusText")||g.statusText):i&&(n=c.getElementsByTagName("pre")[0],o=c.getElementsByTagName("body")[0],n?g.responseText=n.textContent||n.innerText:o&&(g.responseText=o.textContent||o.innerText))}else"xml"===s&&!g.responseXML&&g.responseText&&(g.responseXML=S(g.responseText));try{e=k(g,s,p)}catch(e){r="parsererror",t=e||r,g.error=t}}catch(e){q("error caught: ",e),r="error",t=e||r,g.error=t}g.aborted&&(q("upload aborted"),r=null),g.status&&(r=200<=g.status&&g.status<300||304===g.status?"success":"error"),"success"===r?(p.success&&p.success.call(p.context,e,"success",g),v.resolve(g.responseText,"success",g),h&&L.event.trigger("ajaxSuccess",[g,p])):r&&(void 0===t&&(t=g.statusText),p.error&&p.error.call(p.context,g,r,t),v.reject(g,"error",t),h&&L.event.trigger("ajaxError",[g,p,t])),h&&L.event.trigger("ajaxComplete",[g,p]),h&&!--L.active&&L.event.trigger("ajaxStop"),p.complete&&p.complete.call(p.context,g,r),A=!0,p.timeout&&clearTimeout(j);const l=100;setTimeout(function(){p.iframeTarget?m.attr("src",p.iframeSrc):m.remove(),g.responseXML=null},l)}}}const u=L.parseJSON||function(e){return console.error("jquery.parseJSON is undefined"),null};return k=function(e,t,r){const a=e.getResponseHeader("content-type")||"",n=("xml"===t||!t)&&0<=a.indexOf("xml");let o=n?e.responseXML:e.responseText;return n&&"parsererror"===o.documentElement.nodeName&&L.error&&L.error("parsererror"),r&&r.dataFilter&&(o=r.dataFilter(o,t)),"string"==typeof o&&(("json"===t||!t)&&0<=a.indexOf("json")?o=u(o):("script"===t||!t)&&0<=a.indexOf("javascript")&&L.globalEval(o)),o},v}},L.fn.ajaxForm=function(e,t,r,a){if(("string"==typeof e||!1===e&&0<arguments.length)&&(e={data:t,dataType:r,url:e},"function"==typeof a&&(e.success=a)),(e=e||{}).delegation=e.delegation&&L.isFunction(L.fn.on),e.delegation||0!==this.length)return e.delegation?(L(document).off("submit.form-plugin",this.selector,s).off("click.form-plugin",this.selector,i).on("submit.form-plugin",this.selector,e,s).on("click.form-plugin",this.selector,e,i),this):(e.beforeFormUnbind&&e.beforeFormUnbind(this,e),this.ajaxFormUnbind().on("submit.form-plugin",e,s).on("click.form-plugin",e,i));{const n=this.context,o=this.selector;return!L.isReady&&o?(q("DOM not ready, queuing ajaxForm"),L(function(){L(o,n).ajaxForm(e)}),this):(q("terminating; zero elements found by selector"+(L.isReady?"":" (DOM not ready)")),this)}},L.fn.ajaxFormUnbind=function(){return this.off("submit.form-plugin click.form-plugin")},L.fn.formToArray=function(e,t,r){const a=[];if(0===this.length)return a;const n=this[0];var o=this.attr("id");let s=e||void 0===n.elements?n.getElementsByTagName("*"):n.elements;if(s=s&&L.makeArray(s),!o||!e&&!/(Edge|Trident)\//.test(g.userAgent)||(o=L(':input[form="'+o+'"]').get()).length&&(s=(s||[]).concat(o)),!s||!s.length)return a;L.isFunction(r)&&(s=L.map(s,r));for(const u of s){var{name:i}=u;if(i&&!u.disabled)if(e&&n.clk&&"image"===u.type)n.clk===u&&(a.push({name:i,type:u.type,value:L(u).val()}),a.push({name:i+".x",value:n.clk_x},{name:i+".y",value:n.clk_y}));else{var c=L.fieldValue(u,!0);if(c&&Array.isArray(c)){t&&t.push(u);for(const f of c)a.push({name:i,value:f})}else if(v.fileapi&&"file"===u.type){t&&t.push(u);var l=u.files;if(l.length)for(const p of l)a.push({name:i,type:u.type,value:p});else a.push({name:i,type:u.type,value:""})}else null!=c&&(t&&t.push(u),a.push({name:i,required:u.required,type:u.type,value:c}))}}if(!e&&n.clk){const m=L(n.clk),d=m[0];var{name:r}=d;r&&!d.disabled&&"image"===d.type&&(a.push({name:r,value:m.val()}),a.push({name:r+".x",value:n.clk_x},{name:r+".y",value:n.clk_y}))}return a},L.fn.formSerialize=function(e){return L.param(this.formToArray(e))},L.fn.fieldSerialize=function(a){const n=[];return this.each(function(){var{name:e}=this;if(e){var t=L.fieldValue(this,a);if(t&&Array.isArray(t))for(const r of t)n.push({name:e,value:r});else null!=t&&n.push({name:e,value:t})}}),L.param(n)},L.fn.fieldValue=function(r){const a=[];for(let e=0,t=this.length;e<t;e++){var n=this[e],n=L.fieldValue(n,r);null==n||Array.isArray(n)&&!n.length||(Array.isArray(n)?L.merge(a,n):a.push(n))}return a},L.fieldValue=function(e,t){var{name:r}=e,{type:a}=e,n=e.tagName.toLowerCase();if((t=void 0===t?!0:t)&&(!r||e.disabled||"reset"===a||"button"===a||("checkbox"===a||"radio"===a)&&!e.checked||("submit"===a||"image"===a)&&e.form&&e.form.clk!==e||"select"===n&&e.selectedIndex<0))return null;if("select"!==n)return L(e).val().replace(u,"\r\n");{n=e.selectedIndex;if(n<0)return null;const c=[],l=e.options;var o="select-one"===a,s=o?n+1:l.length;for(let e=o?n:0;e<s;e++){var i=l[e];if(i.selected&&!i.disabled){i=i.value||(i.attributes&&i.attributes.value&&!i.attributes.value.specified?i.text:i.value);if(o)return i;c.push(i)}}return c}},L.fn.clearForm=function(e){return this.each(function(){L("input,select,textarea",this).clearFields(e)})},L.fn.clearFields=L.fn.clearInputs=function(r){const a=/^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i;return this.each(function(){var{type:e}=this,t=this.tagName.toLowerCase();a.test(e)||"textarea"===t?this.value="":"checkbox"===e||"radio"===e?this.checked=!1:"select"===t?this.selectedIndex=-1:"file"===e?/MSIE/.test(g.userAgent)?L(this).replaceWith(L(this).clone(!0)):L(this).val(""):r&&(!0===r&&/hidden/.test(e)||"string"==typeof r&&L(this).is(r))&&(this.value="")})},L.fn.resetForm=function(){return this.each(function(){const t=L(this);var e=this.tagName.toLowerCase();switch(e){case"input":this.checked=this.defaultChecked;case"textarea":return this.value=this.defaultValue,!0;case"option":case"optgroup":{const a=t.parents("select");return a.length&&a[0].multiple?"option"===e?this.selected=this.defaultSelected:t.find("option").resetForm():a.resetForm(),!0}case"select":return t.find("option").each(function(e){if(this.selected=this.defaultSelected,this.defaultSelected&&!t[0].multiple)return t[0].selectedIndex=e,!1}),!0;case"label":{var r=L(t.attr("for"));const n=t.find("input,select,textarea");return r[0]&&n.unshift(r[0]),n.resetForm(),!0}case"form":return"function"!=typeof this.reset&&("object"!=typeof this.reset||this.reset.nodeType)||this.reset(),!0;default:return t.find("form,input,label,select,textarea").resetForm(),!0}})},L.fn.enable=function(e){return void 0===e&&(e=!0),this.each(function(){this.disabled=!e})},L.fn.selected=function(r){return void 0===r&&(r=!0),this.each(function(){var{type:e}=this;if("checkbox"===e||"radio"===e)this.checked=r;else if("option"===this.tagName.toLowerCase()){const t=L(this).parent("select");r&&t[0]&&"select-one"===t[0].type&&t.find("option").selected(!1),this.selected=r}})},L.fn.ajaxSubmit.debug=!1}); //# sourceMappingURL=jquery.form.min.js.map