diff --git a/.github/codeql/jquery-form-queries/JQueryFormSecurity.qll b/.github/codeql/jquery-form-queries/JQueryFormSecurity.qll index 2c64c95..61041ef 100644 --- a/.github/codeql/jquery-form-queries/JQueryFormSecurity.qll +++ b/.github/codeql/jquery-form-queries/JQueryFormSecurity.qll @@ -106,22 +106,59 @@ predicate objectKeyStep(DataFlow::Node pred, DataFlow::Node succ) { } /** - * Holds if `callbacks[i].apply(context, [a, b])` passes `pred` to `succ`, a parameter of a - * function pushed onto `callbacks`. + * A function value tracked from where it is created, through helper returns, parameters and + * imports or exports between modules. + */ +private DataFlow::SourceNode trackedFunction(DataFlow::FunctionNode f, DataFlow::TypeTracker t) { + t.start() and result = f + or + exists(DataFlow::TypeTracker t2 | result = trackedFunction(f, t2).track(t2, t)) +} + +/** + * An array tracked from where it is created, through helper parameters and returns and imports + * or exports between modules. + */ +private DataFlow::SourceNode trackedArray(DataFlow::ArrayCreationNode a, DataFlow::TypeTracker t) { + t.start() and result = a + or + exists(DataFlow::TypeTracker t2 | result = trackedArray(a, t2).track(t2, t)) +} + +/** Holds if `node` may hold the array created at `a`. */ +private predicate isArray(DataFlow::ArrayCreationNode a, DataFlow::Node node) { + trackedArray(a, DataFlow::TypeTracker::end()).flowsTo(node) +} + +/** Holds if `callback` is pushed onto the array created at `list`, wherever either is used. */ +private predicate pushedCallback(DataFlow::ArrayCreationNode list, DataFlow::FunctionNode callback) { + exists(DataFlow::MethodCallNode push | + push.getMethodName() = "push" and + isArray(list, push.getReceiver()) and + trackedFunction(callback, DataFlow::TypeTracker::end()).flowsTo(push.getAnArgument()) + ) +} + +/** + * Holds if `list[i].apply(context, [a, b])` or `list[i].call(context, a, b)` passes `pred` to + * `succ`, a parameter of a function pushed onto `list`. The list, the callbacks and the + * arguments array may each come from another function or module. */ predicate callbackListStep(DataFlow::Node pred, DataFlow::Node succ) { exists( - DataFlow::MethodCallNode apply, DataFlow::ArrayCreationNode args, DataFlow::MethodCallNode push, - DataFlow::FunctionNode callback, Variable list, int i + DataFlow::MethodCallNode invoke, DataFlow::ArrayCreationNode list, + DataFlow::FunctionNode callback, int i | - apply.getMethodName() = "apply" and - refersTo(apply.getReceiver().(DataFlow::PropRead).getBase(), list, "") and - args = apply.getArgument(1).getALocalSource() and - push.getMethodName() = "push" and - refersTo(push.getReceiver(), list, "") and - push.getAnArgument().getALocalSource() = callback and - pred = args.getElement(i) and + isArray(list, invoke.getReceiver().(DataFlow::PropRead).getBase()) and + pushedCallback(list, callback) and succ = callback.getParameter(i) + | + invoke.getMethodName() = "apply" and + exists(DataFlow::ArrayCreationNode args | + isArray(args, invoke.getArgument(1)) and pred = args.getElement(i) + ) + or + invoke.getMethodName() = "call" and pred = invoke.getArgument(i + 1) ) } diff --git a/GLOSSARY.md b/GLOSSARY.md index e72d2b0..24b6c92 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -11,3 +11,7 @@ _Avoid_: master, develop, next (as standing integration branches), trunk (as a b **v4 line**: The 4.x compatibility release line (legacy jQuery and shim support retained). After 5.0 ships, patches still belong to this line. _Avoid_: old major, legacy branch (when meaning the release line rather than a git ref) + +**form member**: +A property or method of a `
` element (such as `elements`, `ownerDocument`, `getAttribute`, `submit`, `reset`) as the DOM defines it, read or called through the DOM prototypes so that a control with the same name cannot shadow it. +_Avoid_: form property (a control named like it replaces `form.name`), form attribute (the HTML attribute is separate) diff --git a/README.md b/README.md index 0a67b2b..fa0dfd9 100644 --- a/README.md +++ b/README.md @@ -14,10 +14,12 @@ Please note that this project is released with a [Contributor Code of Conduct](C ### Security Please report security issues privately, not in public issues. See [SECURITY](SECURITY.md). +Some options must be trusted input only, and a `target` response is inserted as HTML; see [Trusted options](docs/options.md#trusted-options) and the [`target`](docs/options.md#target) sanitizing recipe. Iframe uploads need HTML-safe responses; see [`iframe`](docs/options.md#iframe). + ## Compatibility * Requires jQuery 1.7.2 or later. `main` is tested against jQuery 1.7.2, 3.7.1 and 4.0.0. * jQuery 4 needs 4.4.0 or later; 4.3.0 uses APIs that jQuery 4 removed. -* With `delegation: true` on jQuery 3 and later, every form on the page is handled, not only the selected ones. ([issue #353](https://github.com/jquery-form/form/issues/353)) +* With `delegation: true` on jQuery 3 and later, every form on the page is handled, not only the selected ones; use `delegation: ""` instead. ([issue #353](https://github.com/jquery-form/form/issues/353)) * **Not** compatible with the jQuery slim builds, which leave out AJAX. ## Download @@ -59,6 +61,14 @@ $('form').ajaxForm({ }); ```` +### ajaxFormUnbind( [selector] ) +Removes the handlers `ajaxForm` bound on the selection, and every delegated binding (`delegation: true` or a selector) the plugin made on the document. With a selector string it removes only that delegated binding and leaves the selection's handlers alone. Calling `ajaxForm` again on a form does not remove delegated bindings. + +````javascript +$('#myForm').ajaxFormUnbind(); // the form's handlers and all delegated bindings +$(document).ajaxFormUnbind('form.ajax'); // one delegated binding +```` + ### ajaxSubmit( options ) Immediately submits the form via AJAX. In the most common use case this is invoked in response to the user clicking a submit button on the form. Use ajaxSubmit if you want to bind your own submit handler to the form. @@ -136,18 +146,20 @@ Expected data type of the response. One of: null, 'xml', 'script', or 'json'. Th * 'script': server response is evaluated in the global context ### delegation -true to enable support for event delegation +A selector string, or `true`, to handle forms through a document-level (delegated) binding, so forms added later are handled too. *requires jQuery v1.7+* -**Note:** jQuery 3.0 removed the selector information this option relied on, so on jQuery 3 and later delegation is not limited to the selected forms; every form submit on the page is handled. See `docs/research/selector-context-delegation.md`. +With a selector, a form is submitted through the plugin when it, or an element around it, matches the selector. The selection `ajaxForm` is called on is ignored. Binding the same selector again replaces its options. An empty string throws an error. ````javascript -// prepare all existing and future forms for ajax submission -$('form').ajaxForm({ - delegation: true +// prepare existing and future forms with class "ajax" for ajax submission +$(document).ajaxForm({ + delegation: 'form.ajax' }); ```` +**Warning:** `delegation: true` uses the selection's selector, which jQuery 3.0 removed. On jQuery 3 and later it binds **every form on the page**, so the options (`data`, `headers`) go with any form's submission. The plugin logs a `console.warn` for each such call, even with `debug` off. Use a selector. jQuery 5.0 support will require one. + ### error Callback function to be invoked upon error. It is passed the following arguments: @@ -175,6 +187,9 @@ The HTTP method to use for the request (e.g. 'POST', 'GET', 'PUT'). ### replaceTarget Optionally used along with the target option. Set to true if the target should be replaced or false if only the target contents should be replaced. +### requestFormat +Set to `"json"` to send the fields (repeated names as arrays) merged with object `data` as a JSON body, with `contentType: "application/json; charset=UTF-8"`. Throws with a GET method, string `data`, files or the iframe transport. Based on the idea in PR #557 by zhangciwu. + ### resetForm Boolean flag indicating whether the form should be reset if the submit is successful diff --git a/dist/jquery.form.js b/dist/jquery.form.js index e3afaea..04b8254 100644 --- a/dist/jquery.form.js +++ b/dist/jquery.form.js @@ -1,6 +1,6 @@ /*! * jQuery Form Plugin - * version: 4.4.0 + * version: 4.5.0 * Requires jQuery v1.7.2 or later * Project repository: https://github.com/jquery-form/form @@ -46,1117 +46,2297 @@ } }(function (jQuery) { -(function ($) { 'use strict'; +// Form members: the properties and methods the plugin reads or calls on a form. A control named +// like a member (elements, setAttribute) shadows that member on the form itself, so members are +// read through the DOM prototypes, which a control cannot shadow. - /* - Usage Note: - ----------- - Do not use both ajaxSubmit and ajaxForm on the same form. These - functions are mutually exclusive. Use ajaxSubmit if you want - to bind your own submit handler to the form. For example, +// The prototype chain of a form, nearest first. Looked up on every call: old browsers have no +// DOM prototypes, and tests remove them. +var owners = ["HTMLFormElement", "HTMLElement", "Element", "Node"]; - $(document).ready(function() { - $('#myForm').on('submit', function(e) { - e.preventDefault(); // <-- important - $(this).ajaxSubmit({ - target: '#output' - }); - }); - }); +// A form no control can shadow, for methods when the DOM has no prototypes to read them from. +var plainForm = document.createElement("form"); - Use ajaxForm when you want the plugin to manage all the event binding - for you. For example, +function findDescriptor(name) { + for (var i = 0; i < owners.length; i++) { + var owner = window[owners[i]]; + var descriptor = owner && Object.getOwnPropertyDescriptor(owner.prototype, name); - $(document).ready(function() { - $('#myForm').ajaxForm({ - target: '#output' - }); - }); + if (descriptor) { + return descriptor; + } + } - You can also use ajaxForm with delegation (requires jQuery v1.7+), so the - form does not have to exist when you invoke ajaxForm: + return null; +} - $('#myForm').ajaxForm({ - delegation: true, - target: '#output' - }); +/** + * Reads a member of a form through its prototype getter. + * Falls back to the plain property without DOM prototypes, or on an element the getter does not + * accept (such as a fieldset for `elements`). + */ +function formMember(form, name) { + var descriptor = findDescriptor(name); - When using ajaxForm, the ajaxSubmit function will be invoked for you - at the appropriate time. - */ + try { + return descriptor.get.call(form); + } catch (e) { + return form[name]; + } +} - var rCRLF = /\r?\n/g; +/** + * Calls a method of a form through its prototype, or through an unshadowed form without DOM + * prototypes. + */ +function callFormMethod(form, name) { + var descriptor = findDescriptor(name); + var method = descriptor ? descriptor.value : plainForm[name]; + + return method.apply(form, Array.prototype.slice.call(arguments, 2)); +} + +// Nodes such as the document and text nodes have no tag name (#600). +function tagName(el) { + var name = formMember(el, "tagName"); + + return typeof name === "string" ? name.toLowerCase() : ""; +} + +// Elements only: the subject of formToArray may also be the document or a plain object. +function isElement(node) { + return formMember(node, "nodeType") === 1; +} + +// A control named parentNode makes every parentNode walk (jQuery's trigger and closest among +// them) cycle between the form and the control. +function assertRealParent(el) { + if (el.parentNode !== formMember(el, "parentNode")) { + throw new Error( + 'jquery.form: a form control named "parentNode" hides the form\'s parentNode; rename the control' + ); + } +} - /** - * Feature detection - */ - var feature = {}; +// The element itself or its nearest ancestor with one of the tag names, through the real tree. +function closestByTag(el, names) { + for (var node = el; node; node = formMember(node, "parentNode")) { + if (names.indexOf(tagName(node)) >= 0) { + return node; + } + } - feature.fileapi = $('').get(0).files !== undefined; - feature.formdata = typeof window.FormData !== "undefined"; + return null; +} - var hasProp = !!$.fn.prop; - // Called through the prototype: an extraData key or a form field may be named hasOwnProperty. - var hasOwn = Object.prototype.hasOwnProperty; +// The submitter: the button that submitted a form, captured from ajaxForm's clicks. It is kept in +// a private store and cleared shortly after the click. The form's clk, clk_x and clk_y properties +// are still written for pages that read them, and read when the store has none. + +var storeKey = "jqFormSubmitter"; - // A control named like a form member (elements, setAttribute) shadows that member on the form, - // so forms are read and changed through members a control cannot shadow. - var plainForm = document.createElement("form"); +// Writes a property on the form; a control with that name makes it read-only. +function setExpando(form, name, value) { + try { + form[name] = value; + } catch (ignore) { + // the control keeps the name; the store has the submitter + } +} + +// A property the page set on the form, never a control of the form with that name. +function expando(form, name) { + var value = form[name]; + var els = formMember(form, "elements"); - // Resolves both URLs through anchors, as jQuery does for crossDomain, so IE's anchor quirks - // apply to both sides of the comparison. - function isSameOrigin(url) { - var origin = document.createElement("a"); - var target = document.createElement("a"); + return els && value && els.namedItem(name) === value ? undefined : value; +} - origin.href = window.location.href; - target.href = url; - // IE fills in the host of a relative URL only once the resolved href is assigned back - target.href = target.href; // eslint-disable-line no-self-assign +// Records a submitter for a form until the click window ends. +function record(form, el, x, y) { + jQuery.data(form, storeKey, { el: el, x: x, y: y }); + setExpando(form, "clk", el); - return origin.protocol + "//" + origin.host === target.protocol + "//" + target.host; + if (el.type === "image") { + setExpando(form, "clk_x", x); + setExpando(form, "clk_y", y); } - // Nodes such as the document and text nodes have no tag name (#600). - function tagName(el) { - return typeof el.tagName === "string" ? el.tagName.toLowerCase() : ""; + // clear form vars + setTimeout(function () { + jQuery.data(form, storeKey, null); + setExpando(form, "clk", null); + setExpando(form, "clk_x", null); + setExpando(form, "clk_y", null); + }, 100); +} + +// The clicked point of an image button, relative to the image. +function imagePoint(e, target) { + if (typeof e.offsetX !== "undefined") { + return [e.offsetX, e.offsetY]; } - function formElements(form) { - var proto = window.HTMLFormElement && window.HTMLFormElement.prototype; - var descriptor = proto && Object.getOwnPropertyDescriptor(proto, "elements"); + if (typeof jQuery.fn.offset === "function") { + var offset = jQuery(target).offset(); - try { - return descriptor.get.call(form); - } catch (e) { - // no DOM prototype accessors, or another element with controls such as a fieldset - return form.elements; - } + return [e.pageX - offset.left, e.pageY - offset.top]; } - // attr2 uses prop when it can but checks the return type for - // an expected string. This accounts for the case where a form - // contains inputs with names like "action" or "method"; in those - // cases "prop" returns the element - $.fn.attr2 = function () { - if (!hasProp) { - return this.attr.apply(this, arguments); - } + return [e.pageX - target.offsetLeft, e.pageY - target.offsetTop]; +} - var val = this.prop.apply(this, arguments); +/** + * Records the submit or image button a click event reached, for the form it belongs to. + */ +function captureSubmitter(e) { + // the clicked control, or the button around the clicked content (ex: a span within a button) + var target = closestByTag(e.target, ["button", "input"]); - if ((val && val.jquery) || typeof val === "string") { - return val; - } + // the type property, unlike the attribute, is "submit" for a button without a type (#588) + if (!target || (target.type !== "submit" && target.type !== "image")) { + return; + } - return this.attr.apply(this, arguments); - }; + var form = target.form; - /** - * ajaxSubmit() provides a mechanism for immediately submitting - * an HTML form using AJAX. - * - * @param {object|string} options jquery.form.js parameters or custom url for submission - * @param {object} data extraData - * @param {string} dataType ajax dataType - * @param {function} onSuccess ajax success callback function - */ - $.fn.ajaxSubmit = function (options, data, dataType, onSuccess) { - // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) - if (!this.length) { - log("ajaxSubmit: skipping submit process - no element selected"); + if (!form) { + // a submit control that belongs to no form + return; + } - return this; - } + var point = target.type === "image" ? imagePoint(e, target) : []; - var method, - action, - url, - isMsie, - iframeSrc, - $form = this; - - if (typeof options === "function") { - options = { success: options }; - } else if (typeof options === "string" || (options === false && arguments.length > 0)) { - options = { - url: options, - data: data, - dataType: dataType, - }; + record(form, target, point[0], point[1]); +} - if (typeof onSuccess === "function") { - options.success = onSuccess; - } - } else if (typeof options === "undefined") { - options = {}; - } +/** + * Records the submitter a submit event names (SubmitEvent.submitter), when no click was captured. + * An image submitter gets the point 0,0, as native submission sends it without a click. + */ +function captureEventSubmitter(e, form) { + var el = e.originalEvent && e.originalEvent.submitter; - method = options.method || options.type || this.attr2("method"); - action = options.url || this.attr2("action"); + if (el && !submitterOf(form)) { + record(form, el, 0, 0); + } +} - url = typeof action === "string" ? action.trim() : ""; - // clean url (don't include hash value); an action that is only a fragment means this page - url = url.split("#")[0] || window.location.href.split("#")[0]; - // IE requires javascript:false in https, but this breaks chrome >83 and goes against spec. - // Instead of using javascript:false always, let's only apply it for IE. - isMsie = /(MSIE|Trident)/.test(navigator.userAgent || ""); - iframeSrc = isMsie && /^https/i.test(document.URL) ? "javascript:false" : "about:blank"; // eslint-disable-line no-script-url +/** + * The form's submitter as { el, x, y } (x and y for an image button), or null. + */ +function submitterOf(form) { + if (!form) { + return null; + } - options = $.extend( - true, - { - url: url, - success: $.ajaxSettings.success, - type: method || $.ajaxSettings.type, - iframeSrc: iframeSrc, - }, - options - ); + var stored = jQuery.data(form, storeKey); - // hook for manipulating the form data before it is extracted; - // convenient for use with rich editors like tinyMCE or FCKEditor - var veto = {}; + if (stored) { + return stored; + } - this.trigger("form-pre-serialize", [this, options, veto]); + var el = expando(form, "clk"); - if (veto.veto) { - log("ajaxSubmit: submit vetoed via form-pre-serialize trigger"); + return el ? { el: el, x: expando(form, "clk_x"), y: expando(form, "clk_y") } : null; +} - return this; +/** + * The submitter's fields for a post that adds them itself (the iframe upload), as name → value. + */ +function submitterFields(form) { + var fields = {}; + var sub = submitterOf(form); + var el = sub && sub.el; + + if (el && el.name && !el.disabled) { + fields[el.name] = el.value; + if (el.type === "image") { + fields[el.name + ".x"] = sub.x; + fields[el.name + ".y"] = sub.y; } + } - // provide opportunity to alter form data before it is serialized - if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { - log("ajaxSubmit: submit aborted via beforeSerialize callback"); + return fields; +} - return this; - } +/** + * The form's submitter element, or null. + */ +function submitterElement(form) { + var sub = submitterOf(form); - var traditional = options.traditional; + return sub ? sub.el : null; +} - if (typeof traditional === "undefined") { - traditional = $.ajaxSettings.traditional; - } +// Debug logging, switched on by $.fn.ajaxSubmit.debug. The flag is read on every call, so it can +// be turned on after the plugin loads. +function log() { + if (!jQuery.fn.ajaxSubmit.debug) { + return; + } - var elements = []; - var qx, - a = this.formToArray(options.semantic, elements, options.filtering); + var msg = "[jquery.form] " + Array.prototype.join.call(arguments, ""); - if (options.data) { - var optionsData = typeof options.data === "function" ? options.data(a) : options.data; + if (window.console && window.console.log) { + window.console.log(msg); + } else if (window.opera && window.opera.postError) { + window.opera.postError(msg); + } +} - options.extraData = optionsData; - qx = $.param(optionsData, traditional); - } +var warned = {}; - // give pre-submit callback an opportunity to abort the submit - if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { - log("ajaxSubmit: submit aborted via beforeSubmit callback"); +/** + * A deprecation warning: console.warn, only while debug is on, once per id per page. The message + * names the replacement; the warning adds that the feature is removed in 5.0. + */ +function deprecate(id, message) { + if (!jQuery.fn.ajaxSubmit.debug || warned[id]) { + return; + } - return this; - } + warned[id] = true; - // fire vetoable 'validate' event - this.trigger("form-submit-validate", [a, this, options, veto]); - if (veto.veto) { - log("ajaxSubmit: submit vetoed via form-submit-validate trigger"); + if (window.console && typeof window.console.warn === "function") { + window.console.warn("[jquery.form] " + message + " (removed in 5.0)"); + } +} + +// True for a jQuery version string older than 3.5. +function beforeJQuery35(version) { + var parts = String(version).split("."); + var major = Number(parts[0]); + + return major < 3 || (major === 3 && Number(parts[1]) < 5); +} + +// 5.0 needs jQuery 3.5 or later: warned on the first ajaxSubmit or ajaxForm, given jQuery's version. +function deprecateOldJQuery(version) { + if (beforeJQuery35(version)) { + deprecate( + "jquery", + "support for jQuery " + version + " is deprecated, 5.0 needs jQuery 3.5 or later" + ); + } +} - return this; - } +// The arguments ajaxSubmit and ajaxForm accept in place of an options object. - var q = $.param(a, traditional); +/** + * Turns the (url, data, dataType, success) shorthand into options. A url of false is kept as + * the url; anything else is returned as given. + */ +function shorthandOptions(options, data, dataType, onSuccess) { + if (typeof options !== "string" && options !== false) { + return options; + } - if (qx) { - q = q ? q + "&" + qx : qx; - } + var result = { url: options, data: data, dataType: dataType }; - if (options.type.toUpperCase() === "GET") { - // the query goes before any fragment in the url option - var hashAt = options.url.indexOf("#"); - var base = hashAt < 0 ? options.url : options.url.slice(0, hashAt); + if (typeof onSuccess === "function") { + result.success = onSuccess; + } - options.url = - base + (base.indexOf("?") >= 0 ? "&" : "?") + q + options.url.slice(base.length); - options.data = null; // data is null for 'get' - } else { - options.data = q; // data is the query string for 'post' - } + return result; +} - var callbacks = []; +// A copy of options without its url, so the form action is used. +function withoutUrl(options) { + var result = {}; - if (options.resetForm) { - callbacks.push(function () { - $form.resetForm(); - }); + for (var key in options) { + if (key !== "url" && Object.prototype.hasOwnProperty.call(options, key)) { + result[key] = options[key]; } + } - if (options.clearForm) { - callbacks.push(function () { - $form.clearForm(options.includeHidden); - }); - } + return result; +} - // perform a load on the target only if dataType is not provided - if (!options.dataType && options.target) { - var oldSuccess = options.success || function () {}; +/** + * The options ajaxSubmit starts from: a function is the success callback, the shorthand is + * expanded, and no options at all is an empty object. A url of false or "" means the form action. + */ +function submitOptions(options, data, dataType, onSuccess) { + if (typeof options === "function") { + return { success: options }; + } - callbacks.push(function (data, textStatus, jqXHR) { - var successArguments = arguments, - fn = options.replaceTarget ? "replaceWith" : "html", - $target = $(options.target); + options = shorthandOptions(options, data, dataType, onSuccess); - // Only a string response is inserted. jQuery has already parsed a JSON or XML response, - // and inserting it would parse each of its strings as HTML. - if (typeof data === "string") { - $target[fn](data); - } else { - log("target: the response was parsed by jQuery, so it is not inserted"); - } + if (typeof options === "undefined") { + return {}; + } - $target.each(function () { - oldSuccess.apply(this, successArguments); - }); - }); - } else if (options.success) { - if (Array.isArray(options.success)) { - $.merge(callbacks, options.success); - } else { - callbacks.push(options.success); - } + return options.url === false || options.url === "" ? withoutUrl(options) : options; +} + +/** + * jQuery treats `context` as a flat option: after a deep merge, the settings get back the + * caller's own object from the last source that has one, so `this` in callbacks is that object. + */ +function keepContext(settings, sources) { + for (var i = 0; i < sources.length; i++) { + if (sources[i].context !== undefined) { + settings.context = sources[i].context; } + } - options.success = function (data, status, xhr) { - // jQuery 1.4+ passes xhr as 3rd arg - var context = options.context || this; // jQuery 1.4+ supports scope context + return settings; +} - for (var i = 0, max = callbacks.length; i < max; i++) { - callbacks[i].apply(context, [data, status, xhr || $form, $form]); - } - }; +// ajaxForm binding: the submit and click handlers that send a form through ajaxSubmit. The +// handlers look up $.fn.ajaxSubmit when they run, so a replacement installed later is used. - if (options.error) { - var oldError = options.error; +// Sends the submit event's form with ajaxSubmit, unless an earlier handler cancelled it. +function submitWith(e, options) { + if (!e.isDefaultPrevented()) { + // if event has been canceled, don't proceed + e.preventDefault(); + // the form is found through the real tree: a control named nodeType misleads jQuery's closest + var form = closestByTag(e.target, ["form"]); - options.error = function (xhr, status, error) { - var context = options.context || this; + // a button outside the form (form attribute), or requestSubmit(button), sends no click here + captureEventSubmitter(e, form); + jQuery(form).ajaxSubmit(options); // #365 + } +} + +function doAjaxSubmit(e) { + submitWith(e, e.data); +} + +function captureSubmittingElement(e) { + /* jshint validthis:true */ + assertRealParent(this); + captureSubmitter(e); +} + +// An empty selection: queued until the DOM is ready (old jQuery keeps the selector), or dropped. +function bindLater($sel, options) { + var o = { s: $sel.selector, c: $sel.context }; + + if (!jQuery.isReady && o.s) { + log("DOM not ready, queuing ajaxForm"); + deprecate( + "queue", + "queuing ajaxForm until the DOM is ready is deprecated, call ajaxForm inside $(fn) " + + 'or use delegation: ""' + ); + jQuery(function () { + jQuery(o.s, o.c).ajaxForm(options); + }); - oldError.apply(context, [xhr, status, error, $form]); - }; - } + return $sel; + } - if (options.complete) { - var oldComplete = options.complete; + // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() + log("terminating; zero elements found by selector" + (jQuery.isReady ? "" : " (DOM not ready)")); - options.complete = function (xhr, status) { - var context = options.context || this; + return $sel; +} - oldComplete.apply(context, [xhr, status, $form]); - }; - } +// delegation: true on jQuery 3 and later, where the selection has no selector: always warned, +// debug or not, once per ajaxForm call. +function warnUnscoped() { + var console = window.console || {}; - // are there files to upload? + if (typeof console.warn === "function") { + console.warn( + "[jquery.form] delegation: true binds every form on the page on jQuery 3 and later; " + + 'pass a selector instead, e.g. delegation: "form.ajax"' + ); + } +} - // [value] (issue #113), also see comment: - // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219 - var fileInputs = $("input[type=file]:enabled", this).filter(function () { - return $(this).val() !== ""; - }); - var hasFileInputs = fileInputs.length > 0; - var mp = "multipart/form-data"; - var multipart = $form.attr("enctype") === mp || $form.attr("encoding") === mp; - var fileAPI = feature.fileapi && feature.formdata; +function bindDelegated($sel, options) { + if ($sel.selector === undefined) { + warnUnscoped(); + } - log("fileAPI :" + fileAPI); + jQuery(document) + .off("submit.form-plugin", $sel.selector, doAjaxSubmit) + .off("click.form-plugin", $sel.selector, captureSubmittingElement) + .on("submit.form-plugin", $sel.selector, options, doAjaxSubmit) + .on("click.form-plugin", $sel.selector, options, captureSubmittingElement); - var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI; - var jqxhr; + return $sel; +} - // options.iframe allows user to force iframe mode - // 06-NOV-09: now defaulting to iframe mode if file input is detected - if (options.iframe !== false && (options.iframe || shouldUseFrame)) { - // hack to fix Safari hang (thanks to Tim Molendijk for this) - // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d - if (options.closeKeepAlive) { - $.get(options.closeKeepAlive, function () { - jqxhr = fileUploadIframe(); - }); - } else { - jqxhr = fileUploadIframe(); - } - } else if ((hasFileInputs || multipart) && fileAPI) { - jqxhr = fileUploadXhr(a); - } else { - jqxhr = $.ajax(options); - } +// The element itself or its nearest ancestor that matches the selector. The walk never reads a +// parentNode a control can hide (jQuery's delegated walk does, and cycles on such a form). +function closestMatch(el, selector) { + if (!isElement(el)) { + return null; + } - $form.removeData("jqxhr").data("jqxhr", jqxhr); + if (window.Element && Element.prototype.closest) { + return Element.prototype.closest.call(el, selector); + } - // clear element array - for (var k = 0; k < elements.length; k++) { - elements[k] = null; + for (var node = el; node && isElement(node); node = formMember(node, "parentNode")) { + if (jQuery(node).is(selector)) { + return node; } + } - // fire 'notify' event - this.trigger("form-submit-notify", [this, options]); + return null; +} - return this; +// The document handlers bound for each delegation selector, keyed by "s" + selector. +var delegated = {}; - // utility fn for deep serialization - function deepSerialize(extraData) { - var param = $.param(extraData, traditional); - var serialized = param ? param.split("&") : []; - var len = serialized.length; - var result = []; - var i, part; - - for (i = 0; i < len; i++) { - // #252; undo param space replacement - serialized[i] = serialized[i].replace(/\+/g, " "); - part = serialized[i].split("="); - // #278; use array instead of object storage, favoring array serializations - result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]); - } +function unbindSelector(selector) { + var handlers = delegated["s" + selector]; - return result; - } + if (handlers) { + jQuery(document) + .off("submit.form-plugin", handlers.submit) + .off("click.form-plugin", handlers.click); + delete delegated["s" + selector]; + } +} - // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz) - function fileUploadXhr(a) { - var formdata = new FormData(); +// delegation: "": one handler pair on the document, scoped to the selector. +function bindSelector($sel, selector, options) { + if (!selector) { + throw new Error("jquery.form: delegation needs a selector, or true"); + } - for (var i = 0; i < a.length; i++) { - formdata.append(a[i].name, a[i].value); + var handlers = { + submit: function (e) { + if (closestMatch(e.target, selector)) { + submitWith(e, options); + } + }, + click: function (e) { + if (closestMatch(e.target, selector)) { + captureSubmitter(e); } + }, + }; - if (options.extraData) { - var serializedData = deepSerialize(options.extraData); + unbindSelector(selector); + delegated["s" + selector] = handlers; + jQuery(document) + .on("submit.form-plugin", handlers.submit) + .on("click.form-plugin", handlers.click); - for (i = 0; i < serializedData.length; i++) { - formdata.append(serializedData[i][0], serializedData[i][1]); - } - } + return $sel; +} - options.data = null; +// Passed by ajaxForm's own rebind: unbind the selection only, never the document handlers. +var selectionOnly = {}; - var s = $.extend(true, {}, $.ajaxSettings, options, { - contentType: false, - processData: false, - cache: false, - type: method || "POST", - }); +/** + * ajaxForm() binds the selected forms so a submit is sent with ajaxSubmit, with the clicked + * submit button (and image coordinates) included. The options work as for ajaxSubmit. + */ +function ajaxForm(options, data, dataType, onSuccess) { + deprecateOldJQuery(jQuery.fn.jquery); + options = shorthandOptions(options, data, dataType, onSuccess) || {}; - if (options.uploadProgress) { - // workaround because jqXHR does not expose upload property - s.xhr = function () { - var xhr = $.ajaxSettings.xhr(); - - if (xhr.upload) { - xhr.upload.addEventListener( - "progress", - function (event) { - var percent = 0; - var position = event.loaded || event.position; /* event.position is deprecated */ - var total = event.total; - - if (event.lengthComputable) { - percent = Math.ceil((position / total) * 100); - } - - options.uploadProgress(event, position, total, percent); - }, - false - ); - } + if (typeof options.delegation === "string") { + return bindSelector(this, options.delegation, options); + } - return xhr; - }; - } + options.delegation = options.delegation && typeof jQuery.fn.on === "function"; - s.data = null; + if (!options.delegation && this.length === 0) { + return bindLater(this, options); + } - var beforeSend = s.beforeSend; + if (options.delegation) { + return bindDelegated(this, options); + } - s.beforeSend = function (xhr, o) { - // Send FormData() provided by user - if (options.formData) { - o.data = options.formData; - } else { - o.data = formdata; - } + if (options.beforeFormUnbind) { + options.beforeFormUnbind(this, options); + } - if (beforeSend) { - beforeSend.call(this, xhr, o); - } - }; + return this.ajaxFormUnbind(selectionOnly) + .on("submit.form-plugin", options, doAjaxSubmit) + .on("click.form-plugin", options, captureSubmittingElement); +} - return $.ajax(s); - } - - // private function for handling file uploads (hat tip to YAHOO!) - function fileUploadIframe(a) { - var form = $form[0], - el, - i, - s, - g, - id, - $io, - io, - xhr, - sub, - n, - timeoutHandle, - callbackProcessed; - var deferred = $.Deferred(); - - // #341 - deferred.abort = function (status) { - xhr.abort(status); - }; +/** + * ajaxFormUnbind() removes the handlers ajaxForm bound on the selection and every delegated + * binding on the document. ajaxFormUnbind(selector) removes only that delegation selector. + */ +function ajaxFormUnbind(selector) { + if (typeof selector === "string") { + unbindSelector(selector); - // ensure that every serialized input is still enabled - for (i = 0; i < elements.length; i++) { - el = $(elements[i]); - if (hasProp) { - el.prop("disabled", false); - } else { - el.removeAttr("disabled"); - } - } + return this; + } - s = $.extend(true, {}, $.ajaxSettings, options); - s.context = s.context || s; - id = "jqFormIO" + new Date().getTime(); - var ownerDocument = form.ownerDocument; - var $body = $form.closest("body"); - - if (s.iframeTarget) { - $io = $(s.iframeTarget, ownerDocument); - n = $io.attr2("name"); - if (!n) { - $io.attr2("name", id); - } else { - id = n; - } + if (selector !== selectionOnly) { + delegated = {}; + jQuery(document).off("submit.form-plugin click.form-plugin"); + } + + return this.off("submit.form-plugin click.form-plugin"); +} + +/** + * An attribute of a form, or undefined when it is absent, as jQuery's attr returns it. The + * subject may also be the document or a plain object, read through jQuery. + */ +function formAttribute(form, name) { + if (!isElement(form)) { + return jQuery(form).attr(name); + } + + var value = callFormMethod(form, "getAttribute", name); + + return value === null ? undefined : value; +} + +// Successful controls: which controls of a form are sent, and as which name/value fields +// (https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constructing-the-form-data-set). + +// Line breaks, sent as CRLF +var rLineBreak = /\r\n|\r|\n/g; +var rCR = /\r/g; + +// Listed form elements that are never submitted. +var rUnsubmittable = /^(?:fieldset|object|output)$/; + +/** + * Whether a control or option is disabled, also through a disabled fieldset or optgroup. Without + * selector matching, only its own disabled property is read. + */ +function isDisabled(el) { + return typeof el.matches === "function" ? el.matches(":disabled") : !!el.disabled; +} + +/** + * The successful-control rule: whether a control is sent. `submitter` is the button that + * submitted the control's form; other submit and image buttons of a form are not sent. + */ +function isSuccessful(el, submitter) { + var t = el.type; + + if (!el.name || isDisabled(el) || t === "reset" || t === "button") { + return false; + } + + if (t === "checkbox" || t === "radio") { + return !!el.checked; + } + + if (t === "submit" || t === "image") { + return !el.form || submitter === el; + } + + return tagName(el) !== "select" || el.selectedIndex !== -1; +} + +// The value of a select: the selected option's value for one, a list for several. +function selectValue(el) { + var index = el.selectedIndex; + + if (index < 0) { + return null; + } + + var a = [], + ops = el.options; + var one = el.type === "select-one"; + var max = one ? index + 1 : ops.length; + + for (var i = one ? index : 0; i < max; i++) { + var op = ops[i]; + + if (op.selected && !isDisabled(op)) { + var v = op.value; + + if (!v) { + // extra pain for IE... + v = + op.attributes && op.attributes.value && !op.attributes.value.specified + ? op.text + : op.value; + } + + if (one) { + return v; + } + + a.push(v); + } + } + + return a; +} + +/** + * The value of a control, whether or not it is successful: a list for a multiple select, null + * for a select with nothing selected, otherwise a string with CRLF line breaks (a lone CR or LF + * included). + */ +function valueOf(el) { + if (tagName(el) === "select") { + return selectValue(el); + } + + var v = jQuery(el).val(); + var raw = el.value; + + // jQuery before 4.0 drops carriage returns from .val(); read them from the value itself + if (typeof raw === "string" && raw.replace(rCR, "") === v) { + v = raw; + } + + return v.replace(rLineBreak, "\r\n"); +} + +/** + * The fields as a urlencoded body sends them: a selected file as its name. + */ +function urlencodedFields(fields) { + return jQuery.map(fields, function (field) { + return field.type === "file" && typeof field.value !== "string" + ? { name: field.name, value: field.value.name } + : field; + }); +} + +/** + * The serialization steps. `feature` holds what the entry detected at load (fileapi). + */ +function createSuccessfulControls(feature) { + var $ = jQuery; + + // #386; inputs that name the form in their form attribute, other than the candidates found. + // A form only gets the ones it owns. + function outsideControls(formId, els, owner) { + // hat tip @thet; the id is compared, never built into a selector + return $(":input[form]") + .filter(function () { + return ( + this.getAttribute("form") === formId && + (!owner || this.form === owner) && + $.inArray(this, els) < 0 + ); + }) + .get(); + } + + // A descendant of a form is a candidate unless it is a control another form owns. + function ownedBy(els, owner) { + return $.grep(els, function (el) { + return typeof el.form === "undefined" || el.form === owner; + }); + } + + /** + * The candidate controls of a form, in order: its elements, or every descendant it owns in + * semantic mode, then the outside controls it owns that name it. + */ + function controlsOf(form, semantic) { + var formId = formAttribute(form, "id"); + var els = formMember(form, "elements"); + + if (semantic || typeof els === "undefined") { + // the document is not an element; it has its own getElementsByTagName + els = isElement(form) + ? callFormMethod(form, "getElementsByTagName", "*") + : form.getElementsByTagName("*"); + } + + els = $.makeArray(els); + + // the subject may also be a fieldset, the document or another container + var owner = tagName(form) === "form" ? form : null; + + if (semantic && owner) { + els = ownedBy(els, owner); + } + + // FinesseRus: in non-IE browsers outside fields are already included in form.elements. + if (formId && (semantic || /(Edge|Trident)\//.test(navigator.userAgent))) { + els = els.concat(outsideControls(formId, els, owner)); + } + + return els; + } + + // The fields of a control's value, or null when the control is not sent. + function fieldsOf(el) { + var n = el.name; + // read at call time, so a page that replaces $.fieldValue changes what is sent + var v = $.fieldValue(el, true); + + if (v && v.constructor === Array) { + return $.map(v, function (value) { + return { name: n, value: value }; + }); + } + + if (feature.fileapi && el.type === "file") { + var files = el.files; + + // #180: an empty field when no file is selected + return files.length + ? $.map(files, function (file) { + return { name: n, value: file, type: el.type }; + }) + : [{ name: n, value: "", type: el.type }]; + } + + if (v === null || typeof v === "undefined") { + return null; + } + + return [{ name: n, value: v, type: el.type, required: el.required }]; + } + + // The clicked image's value and coordinates. + function imageFields(sub, input, type) { + var n = input.name; + var value = { name: n, value: $(input).val() }; + + if (type) { + value.type = type; + } + + return [value, { name: n + ".x", value: sub.x }, { name: n + ".y", value: sub.y }]; + } + + // Adds one candidate control's fields, and the control when it has a value to send. + function addCandidate(collected, form, el, semantic) { + if (!el.name || isDisabled(el) || rUnsubmittable.test(tagName(el))) { + return; + } + + var sub = semantic && el.type === "image" && submitterOf(form); + + if (sub) { + // handle image inputs on the fly when semantic == true + if (sub.el === el) { + collected.fields.push.apply(collected.fields, imageFields(sub, el, el.type)); + } + + return; + } + + var own = fieldsOf(el); + + if (own) { + collected.controls.push(el); + collected.fields.push.apply(collected.fields, own); + } + } + + // input type=='image' are not found in elements array! handle it here + function addClickedImage(collected, form) { + var sub = submitterOf(form); + var input = sub && $(sub.el)[0]; + + if (input && input.name && !isDisabled(input) && input.type === "image") { + collected.fields.push.apply(collected.fields, imageFields(sub, input)); + } + } + + /** + * The fields of a form, as formToArray returns them, and the controls they came from. + */ + function collect(form, semantic, filtering) { + var collected = { fields: [], controls: [] }; + + if (!form) { + return collected; + } + + var els = controlsOf(form, semantic); + + if (typeof filtering === "function") { + els = $.map(els, filtering); + } + + for (var i = 0; i < els.length; i++) { + addCandidate(collected, form, els[i], semantic); + } + + if (!semantic) { + addClickedImage(collected, form); + } + + return collected; + } + + return { + controlsOf: controlsOf, + fieldsOf: fieldsOf, + collect: collect, + }; +} + +// The XMLHttpRequest transports: $.ajax with the encoded fields, or FormData for file uploads. +var $$4 = jQuery; + +// utility fn for deep serialization: [name, value] pairs, as $.param encodes them +function deepSerialize(extraData, traditional) { + var param = $$4.param(extraData, traditional); + var serialized = param ? param.split("&") : []; + var len = serialized.length; + var result = []; + var i, part; + + for (i = 0; i < len; i++) { + // #252; undo param space replacement + serialized[i] = serialized[i].replace(/\+/g, " "); + part = serialized[i].split("="); + // #278; use array instead of object storage, favoring array serializations + result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]); + } + + return result; +} + +/** + * Posts the fields and extraData as FormData, for files with the File API. + * XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz) + */ +function sendFormData(submission) { + var options = submission.options; + var a = submission.fields; + + var formdata = new FormData(); + + for (var i = 0; i < a.length; i++) { + formdata.append(a[i].name, a[i].value); + } + + if (options.extraData) { + var serializedData = deepSerialize(options.extraData, submission.traditional); + + for (i = 0; i < serializedData.length; i++) { + formdata.append(serializedData[i][0], serializedData[i][1]); + } + } + + options.data = null; + + var s = $$4.extend(true, {}, $$4.ajaxSettings, options, { + contentType: false, + processData: false, + cache: false, + type: submission.method || "POST", + }); + + keepContext(s, [$$4.ajaxSettings, options]); + + if (options.uploadProgress) { + // workaround because jqXHR does not expose upload property: wraps the xhr factory, the + // caller's or jQuery's + var createXhr = s.xhr; + + s.xhr = function () { + var xhr = createXhr.call(this); + + if (xhr.upload) { + xhr.upload.addEventListener( + "progress", + function (event) { + var percent = 0; + // event.position is the deprecated name, read only when loaded is missing + var position = event.loaded !== undefined ? event.loaded : event.position; + var total = event.total; + + if (event.lengthComputable) { + percent = Math.ceil((position / total) * 100); + } + + options.uploadProgress(event, position, total, percent); + }, + false + ); + } + + return xhr; + }; + } + + s.data = null; + + var beforeSend = s.beforeSend; + + s.beforeSend = function (xhr, o) { + // Send FormData() provided by user + if (options.formData) { + o.data = options.formData; + } else { + o.data = formdata; + } + + // a veto (false) cancels the upload, as on the other transports + return beforeSend ? beforeSend.call(this, xhr, o) : undefined; + }; + + return $$4.ajax(s); +} + +/** + * Sends the encoded fields with $.ajax. + */ +function sendAjax(submission) { + return $$4.ajax(submission.options); +} + +// The iframe form post: the extra fields (submitter, CSRF, data), the form attributes set while +// posting and restored after, and the native submit. +var $$3 = jQuery; + +// The form attributes an iframe upload changes while it posts. +var uploadAttributes = ["action", "target", "method", "enctype", "encoding"]; + +// Called through the prototype: an extraData key or a form field may be named hasOwnProperty. +var hasOwn = Object.prototype.hasOwnProperty; + +function isGet(method) { + return /^get$/i.test(method); +} + +// Resolves both URLs through anchors, as jQuery does for crossDomain, so IE's anchor quirks +// apply to both sides of the comparison. +function isSameOrigin(url) { + var origin = document.createElement("a"); + var target = document.createElement("a"); + + origin.href = window.location.href; + target.href = url; + // IE fills in the host of a relative URL only once the resolved href is assigned back + target.href = target.href; // eslint-disable-line no-self-assign + + return origin.protocol + "//" + origin.host === target.protocol + "//" + target.host; +} + +/** Adds the clicked submitter (and an image's coordinates) to s.extraData. */ +function addSubmitterFields(s, form) { + // add submitting element to data if we know it + var fields = submitterFields(form); + + for (var n in fields) { + s.extraData = s.extraData || {}; + s.extraData[n] = fields[n]; + } +} + +/** Adds the page's CSRF token to s.extraData when the form is posted to the page's origin. */ +function addCsrfField(s, form, method, forms) { + // Rails CSRF hack (thanks to Yvan Barthelemy); like jquery-ujs, only for the page's origin and + // only when the form is posted, since a get form would put the token in the url + var csrf_token = $$3("meta[name=csrf-token]").attr("content"); + var csrf_param = $$3("meta[name=csrf-param]").attr("content"); + var posts = + !isGet(method) && + (!method || /post/i.test(method) || /post/i.test(forms.property(form, "method"))); + + if (csrf_param && csrf_token && posts && isSameOrigin(s.url)) { + s.extraData = s.extraData || {}; + s.extraData[csrf_param] = csrf_token; + } +} + +function setFormAttribute(form, name, value) { + callFormMethod(form, "setAttribute", name, value); +} + +/** The raw attributes the upload changes, null when absent, to put back exactly (#380). */ +function saveAttributes(form) { + var saved = {}; + + $$3.each(uploadAttributes, function (i, name) { + saved[name] = callFormMethod(form, "hasAttribute", name) + ? callFormMethod(form, "getAttribute", name) + : null; + }); + + return saved; +} + +/** Puts back the attributes saveAttributes recorded, removing those that were absent. */ +function restoreAttributes(form, saved) { + $$3.each(uploadAttributes, function (i, name) { + if (saved[name] === null) { + callFormMethod(form, "removeAttribute", name); + } else { + setFormAttribute(form, name, saved[name]); + } + }); +} + +/** Points the form at the frame `target` with the upload's url, method and encoding. */ +function setUploadAttributes(form, target, method, s, forms) { + var mp = "multipart/form-data"; + + // update form attrs in IE friendly way + setFormAttribute(form, "target", target); + if (!method || /post/i.test(method)) { + setFormAttribute(form, "method", "POST"); + } else if (isGet(method) && !isGet(forms.property(form, "method"))) { + // a form posts natively only with GET or POST; other verbs keep the form's own method + setFormAttribute(form, "method", "GET"); + } + setFormAttribute(form, "action", s.url); + + // ie borks in some cases when setting encoding + if (!s.skipEncodingOverride && (!method || /post/i.test(method))) { + setFormAttribute(form, "encoding", mp); + setFormAttribute(form, "enctype", mp); + } +} + +/** Appends a hidden input per extraData field to the form; each input is pushed onto `added`. */ +function addExtraInputs(form, ownerDocument, extraData, traditional, added) { + // Builds the input with DOM properties: a name is never parsed as HTML. + function addHiddenInput(name, value) { + var input = ownerDocument.createElement("input"); + + input.type = "hidden"; + input.name = name; + added.push($$3(input).val(value).appendTo(form)[0]); + } + + if (extraData) { + for (var n in extraData) { + if (hasOwn.call(extraData, n)) { + // if using the $.param format that allows for multiple values with the same name + if ( + $$3.isPlainObject(extraData[n]) && + hasOwn.call(extraData[n], "name") && + hasOwn.call(extraData[n], "value") + ) { + addHiddenInput(extraData[n].name, extraData[n].value); + } else { + // arrays and objects become one field per value, as $.param sends them (#597) + var single = {}; + + single[n] = extraData[n]; + var fields = deepSerialize(single, traditional); + + for (var f = 0; f < fields.length; f++) { + addHiddenInput(fields[f][0], fields[f][1]); + } + } + } + } + } +} + +/** Submits the form natively, even when a control named submit hides the method. */ +function submitForm(form) { + try { + form.submit(); + } catch (err) { + // just in case form has element with name/id of 'submit' + callFormMethod(form, "submit"); + } +} + +// The iframe response reader: turns the frame's document into the mock xhr's text, XML, status +// and dataType, then parses it as $.ajax would (dataFilter, JSON, script). +var $$2 = jQuery; + +/** The frame's document, or null when the browser denies access to it. */ +function getDoc(frame) { + /* it looks like contentWindow or contentDocument do not + * carry the protocol property in ie8, when running under ssl + * frame.document is the only valid response document, since + * the protocol is know but not on the other two objects. strange? + * "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy + */ + + var doc = null; + + // IE8 cascading access check + try { + if (frame.contentWindow) { + doc = frame.contentWindow.document; + } + } catch (err) { + // IE8 access denied under ssl & missing protocol + log("cannot get iframe.contentWindow document: " + err); + } + + if (doc) { + // successful getting content + return doc; + } + + try { + // simply checking may throw in ie8 under ssl or mismatched protocol + doc = frame.contentDocument ? frame.contentDocument : frame.document; + } catch (err) { + // last attempt + log("cannot get iframe.contentDocument: " + err); + doc = frame.document; + } + + return doc; +} + +/** Parses the response text or XML for the given (lowercase) dataType. */ +function httpData(xhr, type, s) { + // mostly lifted from jq1.4.4 + + var ct = xhr.getResponseHeader("content-type") || "", + xml = (type === "xml" || !type) && ct.indexOf("xml") >= 0, + data = xml ? xhr.responseXML : xhr.responseText; + + if (xml && data.documentElement.nodeName === "parsererror") { + if ($$2.error) { + $$2.error("parsererror"); + } + } + if (s && s.dataFilter) { + data = s.dataFilter(data, type); + } + if (typeof data === "string") { + if ((type === "json" || !type) && ct.indexOf("json") >= 0) { + data = JSON.parse(data); + } else if (type === "script") { + $$2.globalEval(data); + } + } + + return data; +} + +// Copies the status and statusText attributes of an element onto the mock xhr. +function readStatus(xhr, el) { + // support for XHR 'status' & 'statusText' emulation : + xhr.status = Number(el.getAttribute("status")) || xhr.status; + xhr.statusText = el.getAttribute("statusText") || xhr.statusText; +} + +// Fills the mock xhr from the document itself. +function readDocument(doc, xhr, s, isXml) { + var docRoot = doc.body ? doc.body : doc.documentElement; + + xhr.responseText = docRoot ? docRoot.innerHTML : null; + xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; + if (isXml) { + s.dataType = "xml"; + } + xhr.getResponseHeader = function (header) { + // the dataType in lowercase, as $.ajax reads it + var headers = { "content-type": s.dataType && s.dataType.toLowerCase() }; + + return headers[header.toLowerCase()]; + }; + if (docRoot) { + readStatus(xhr, docRoot); + } +} + +// A response embedded in a textarea, or text wrapped in pre or body, replaces responseText. +function readEmbedded(doc, xhr, dt, s) { + var scr = /(json|script|text)/.test(dt); + + if (!scr && !s.textarea) { + return; + } + // see if user embedded response in textarea + var ta = doc.getElementsByTagName("textarea")[0]; + + if (ta) { + xhr.responseText = ta.value; + readStatus(xhr, ta); + } else if (scr) { + // account for browsers injecting pre around json response + var pre = doc.getElementsByTagName("pre")[0]; + var b = doc.getElementsByTagName("body")[0]; + + if (pre) { + xhr.responseText = pre.textContent ? pre.textContent : pre.innerText; + } else if (b) { + xhr.responseText = b.textContent ? b.textContent : b.innerText; + } + } +} + +/** + * Reads and parses the response document into the mock xhr. Returns {status, data, errMsg}, or + * null when `retry()` asks to read the document again later (Opera's untraversable DOM). + */ +function readResponse(doc, xhr, s, retry) { + var status = "success", + data, + errMsg; + + try { + var isXml = /^xml$/i.test(s.dataType) || doc.XMLDocument || $$2.isXMLDoc(doc); + + log("isXml=" + isXml); + + if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) { + // in some browsers (Opera) the iframe DOM is not always traversable when + // the onload callback fires, so we loop a bit to accommodate + if (retry()) { + return null; + } + // let this fall through because server response could be an empty document + } + + readDocument(doc, xhr, s, isXml); + + var dt = (s.dataType || "").toLowerCase(); + + readEmbedded(doc, xhr, dt, s); + + try { + data = httpData(xhr, dt, s); + } catch (err) { + status = "parsererror"; + xhr.error = errMsg = err || status; + } + } catch (err) { + log("error caught: ", err); + status = "error"; + xhr.error = errMsg = err; + } + + return { status: status, data: data, errMsg: errMsg }; +} + +// The iframe upload's lifecycle: the mock xhr and the Deferred, the global ajax events, the +// beforeSend veto, the timeout, abort and settling. +var $$1 = jQuery; + +/** + * Creates the lifecycle of one upload with the merged settings `s`. `frame.stop()` stops the + * frame's load and `frame.release()` removes or resets the frame after the upload. + */ +function createLifecycle(s, frame) { + var g, + timeoutHandle, + callbackProcessed, + deferred = $$1.Deferred(); + + var xhr = { + // mock object + aborted: 0, + responseText: null, + responseXML: null, + status: 0, + statusText: "n/a", + getAllResponseHeaders: function () {}, + getResponseHeader: function () {}, + setRequestHeader: function () {}, + abort: function (status) { + abort(status, [xhr, "aborted", status]); + }, + }; + + // #341 + deferred.abort = function (status) { + xhr.abort(status); + }; + + function done() { + return xhr.aborted || callbackProcessed; + } + + // Completes an aborted upload once and rejects the Deferred with `rejection`. + // `textStatus` replaces the default "timeout"/"aborted" text status. + function abort(status, rejection, textStatus) { + var e = textStatus || (status === "timeout" ? "timeout" : "aborted"); + + if (done()) { + return; + } + + log("aborting upload... " + e); + xhr.aborted = 1; + frame.stop(); + xhr.error = e; + if (s.error) { + s.error.call(s.context, xhr, e, status); + } + deferred.reject.apply(deferred, rejection); + + if (g) { + $$1.event.trigger("ajaxError", [xhr, s, e]); + } + + complete(e); + } + + // The global events that end every upload, cancelled ones included. + function endGlobalEvents() { + if (g) { + $$1.event.trigger("ajaxComplete", [xhr, s]); + } + + if (g && !--$$1.active) { + $$1.event.trigger("ajaxStop"); + } + } + + // The steps every finished or aborted upload ends with, in $.ajax order. + function complete(status) { + if (s.complete) { + s.complete.call(s.context, xhr, status); + } + + endGlobalEvents(); + clearTimeout(timeoutHandle); + + // clean up + setTimeout(function () { + frame.release(); + xhr.responseXML = null; + }, 100); + } + + // A beforeSend veto ends the upload as $.ajax cancels a request: no callbacks, the global + // events end with ajaxError "canceled". + function cancel() { + if (done()) { + return; + } + + callbackProcessed = true; + deferred.reject(); + if (g) { + $$1.event.trigger("ajaxError", [xhr, s, "canceled"]); + } + endGlobalEvents(); + } + + // Fires the start events and beforeSend; false when the upload must not be posted. + function start() { + g = s.global; + // trigger ajax global events so that activity/block indicators work like normal + if (g && $$1.active++ === 0) { + $$1.event.trigger("ajaxStart"); + } + + if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { + cancel(); + + return false; + } + + if (xhr.aborted) { + // abort() in beforeSend already completed the upload + return false; + } + + if (g) { + $$1.event.trigger("ajaxSend", [xhr, s]); + } + + // an ajaxSend handler may abort too + return !xhr.aborted; + } + + // Resolves the upload; returns {error} when the success callback threw. + function succeed(data) { + var failure; + + try { + s.success.call(s.context, data, "success", xhr); + } catch (err) { + failure = { error: err }; + } + + deferred.resolve(xhr.responseText, "success", xhr); + + if (g) { + $$1.event.trigger("ajaxSuccess", [xhr, s, data]); + } + + return failure; + } + + // Settles the upload with the response reader's {status, data, errMsg}. + function settle(result) { + var status = result.status, + errMsg = result.errMsg; + + if (xhr.aborted) { + // abort() completed the upload while its response was processed + log("upload aborted"); + + return; + } + + // an emulated HTTP error status wins, as in $.ajax; a parse error is kept otherwise + if (xhr.status && !((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)) { + status = "error"; + } + + callbackProcessed = true; + + // ordering of these callbacks/triggers is odd, but that's how $.ajax does it + if (status === "success") { + var failure = succeed(result.data); + + complete(status); + if (failure) { + // the upload is settled; the success callback's exception still reaches the console + throw failure.error; + } + + return; + } + + if (typeof errMsg === "undefined") { + errMsg = xhr.statusText; + } + if (s.error) { + s.error.call(s.context, xhr, status, errMsg); + } + deferred.reject(xhr, "error", errMsg); + if (g) { + $$1.event.trigger("ajaxError", [xhr, s, errMsg]); + } + + complete(status); + } + + return { + xhr: xhr, + deferred: deferred, + start: start, + done: done, + abort: abort, + settle: settle, + // Settles an upload that failed with an exception (ignored once aborted). + fail: function (err) { + settle({ status: "error", errMsg: err }); + }, + // Runs `onTimeout` after s.timeout, when set. + startTimer: function (onTimeout) { + if (s.timeout) { + timeoutHandle = setTimeout(onTimeout, s.timeout); + } + }, + stopTimer: function () { + clearTimeout(timeoutHandle); + timeoutHandle = undefined; + }, + }; +} + +// The iframe transport: posts the form itself into a hidden frame and reads the response from it, +// for file uploads without the File API or when the iframe option asks for it. +var $ = jQuery; + +/** + * The iframe send step. `hasProp` is what the entry detected at load; `forms.property` reads a + * form property as attr2 does. + */ +function createIframeTransport(hasProp, forms) { + var CLIENT_TIMEOUT_ABORT = 1; + var SERVER_ABORT = 2; + // tells apart the frames of uploads that start in the same millisecond + var frameCount = 0; + + // ensure that every serialized input is still enabled + function enableControls(elements) { + for (var i = 0; i < elements.length; i++) { + var el = $(elements[i]); + + if (hasProp) { + el.prop("disabled", false); } else { - io = ownerDocument.createElement("iframe"); - io.setAttribute("name", id); - io.setAttribute("src", s.iframeSrc); - $io = $(io); - $io.css({ position: "absolute", top: "-1000px", left: "-1000px" }); + el.removeAttr("disabled"); } - io = $io[0]; + } + } - xhr = { - // mock object - aborted: 0, - responseText: null, - responseXML: null, - status: 0, - statusText: "n/a", - getAllResponseHeaders: function () {}, - getResponseHeader: function () {}, - setRequestHeader: function () {}, - abort: function (status) { - abortUpload(status, [xhr, "aborted", status]); - }, - }; + // Names the frame's window, when the page may: a cross-origin or sandboxed frame refuses. + function nameWindow(frame, name) { + try { + if (frame.contentWindow) { + frame.contentWindow.name = name; + } + } catch (ignore) {} + } - // Completes an aborted upload once and rejects the Deferred with `rejection`. - function abortUpload(status, rejection) { - var e = status === "timeout" ? "timeout" : "aborted"; + // The frame the form posts into: the iframeTarget, named `id` when it has no name, or a new + // hidden frame named `id`. Returns the frame and the name the form targets. + function createFrame(s, id, ownerDocument) { + var $io, n; - if (xhr.aborted || callbackProcessed) { - return; - } + if (s.iframeTarget) { + $io = $(s.iframeTarget, ownerDocument); + n = $io.attr("name"); + if (!n) { + $io.attr("name", id); + // a frame already in the page keeps the browsing context name it was inserted with + $io.each(function () { + nameWindow(this, id); + }); + } else { + id = n; + } + } else { + var io = ownerDocument.createElement("iframe"); + + io.setAttribute("name", id); + io.setAttribute("src", s.iframeSrc); + $io = $(io); + $io.css({ position: "absolute", top: "-1000px", left: "-1000px" }); + } - log("aborting upload... " + e); - xhr.aborted = 1; + return { $io: $io, id: id }; + } + // The frame hooks the lifecycle calls: stop a load in progress, and release after the upload. + function frameHooks(s, $io) { + return { + stop: function () { try { // #214, #257 - if (io.contentWindow.document.execCommand) { - io.contentWindow.document.execCommand("Stop"); + if ($io[0].contentWindow.document.execCommand) { + $io[0].contentWindow.document.execCommand("Stop"); } } catch (ignore) {} $io.attr("src", s.iframeSrc); // abort op in progress - xhr.error = e; - if (s.error) { - s.error.call(s.context, xhr, e, status); + }, + release: function () { + if (!s.iframeTarget) { + $io.remove(); + } else { + // adding else to clean up existing iframe response. + $io.attr("src", s.iframeSrc); } - deferred.reject.apply(deferred, rejection); + }, + }; + } - if (g) { - $.event.trigger("ajaxError", [xhr, s, e]); - } + function listen(io, cb) { + if (io.attachEvent) { + io.attachEvent("onload", cb); + } else { + io.addEventListener("load", cb, false); + } + } - complete(e); - } + function unlisten(io, cb) { + if (io.detachEvent) { + io.detachEvent("onload", cb); + } else { + io.removeEventListener("load", cb, false); + } + } - // The steps every finished or aborted upload ends with, in $.ajax order. - function complete(status) { - if (g) { - $.event.trigger("ajaxComplete", [xhr, s]); - } + // private function for handling file uploads (hat tip to YAHOO!) + function fileUploadIframe(submission) { + var form = submission.form, + method = submission.method; + + var s = keepContext($.extend(true, {}, $.ajaxSettings, submission.options), [ + $.ajaxSettings, + submission.options, + ]); + + s.context = s.context || s; + var ownerDocument = formMember(form, "ownerDocument"); + var $body = $(closestByTag(form, ["body"])); + var frame = createFrame(s, "jqFormIO" + new Date().getTime() + frameCount++, ownerDocument); + var $io = frame.$io, + io = $io[0]; + var life = createLifecycle(s, frameHooks(s, $io)); + var domCheckCount = 50; + + if (!life.start()) { + return life.deferred; + } + + addSubmitterFields(s, form); + addCsrfField(s, form, method, forms); - if (g && !--$.active) { - $.event.trigger("ajaxStop"); + // look for server aborts + function checkState() { + try { + var state = getDoc(io).readyState; + + log("state = " + state); + if (state && state.toLowerCase() === "uninitialized") { + setTimeout(checkState, 50); } + } catch (e) { + log("Server abort: ", e, " (", e.name, ")"); + cb(SERVER_ABORT); + life.stopTimer(); + } + } + + // take a breath so that pending repaints get some cpu time before the upload starts + function doSubmit() { + var saved = saveAttributes(form); - if (s.complete) { - s.complete.call(s.context, xhr, status); + setUploadAttributes(form, frame.id, method, s, forms); + + // support timout + life.startTimer(function () { + cb(CLIENT_TIMEOUT_ABORT); + }); + + // add "extra" data to form if provided in options + var extraInputs = []; + + try { + addExtraInputs(form, ownerDocument, s.extraData, submission.traditional, extraInputs); + + if (!s.iframeTarget) { + // add iframe to doc and submit the form + $io.appendTo($body); } - if (s.timeout) { - clearTimeout(timeoutHandle); + // A connected form posting into a frame outside the document opens a new window. + var root = ownerDocument.documentElement; + + if (io && $.contains(root, form) && !$.contains(root, io)) { + var notInDocument = "jquery.form: the upload frame is not in the document"; + + life.abort(notInDocument, [life.xhr, "error", notInDocument], "error"); + + return; } - // clean up - setTimeout(function () { - if (!s.iframeTarget) { - $io.remove(); - } else { - // adding else to clean up existing iframe response. - $io.attr("src", s.iframeSrc); - } - xhr.responseXML = null; - }, 100); + listen(io, cb); + setTimeout(checkState, 15); + submitForm(form); + } finally { + // reset attrs and remove "extra" input elements + restoreAttributes(form, saved); + $(extraInputs).remove(); } + } - g = s.global; - // trigger ajax global events so that activity/block indicators work like normal - if (g && $.active++ === 0) { - $.event.trigger("ajaxStart"); - } - if (g) { - $.event.trigger("ajaxSend", [xhr, s]); + // Reads the next document by Opera's rules: false once the retries are used up. + function retry() { + if (--domCheckCount) { + log("requeing onLoad callback, DOM not available"); + setTimeout(cb, 250); + + return true; } - if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { - if (s.global) { - $.active--; - } - deferred.reject(); + return false; + } - return deferred; + function cb(e) { + if (life.done()) { + return; } - if (xhr.aborted) { - // abort() in beforeSend already rejected the Deferred - return deferred; + var doc = getDoc(io); + + if (!doc) { + log("cannot access response document"); + e = SERVER_ABORT; } + if (e === CLIENT_TIMEOUT_ABORT) { + life.abort("timeout", [life.xhr, "timeout"]); - // add submitting element to data if we know it - sub = form.clk; - if (sub) { - n = sub.name; - if (n && !sub.disabled) { - s.extraData = s.extraData || {}; - s.extraData[n] = sub.value; - if (sub.type === "image") { - s.extraData[n + ".x"] = form.clk_x; - s.extraData[n + ".y"] = form.clk_y; - } - } + return; } + if (e === SERVER_ABORT) { + life.abort("server abort", [life.xhr, "error", "server abort"]); - var CLIENT_TIMEOUT_ABORT = 1; - var SERVER_ABORT = 2; + return; + } - function getDoc(frame) { - /* it looks like contentWindow or contentDocument do not - * carry the protocol property in ie8, when running under ssl - * frame.document is the only valid response document, since - * the protocol is know but not on the other two objects. strange? - * "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy - */ + if (doc.location.href === s.iframeSrc) { + // response not received yet + return; + } - var doc = null; + unlisten(io, cb); - // IE8 cascading access check - try { - if (frame.contentWindow) { - doc = frame.contentWindow.document; - } - } catch (err) { - // IE8 access denied under ssl & missing protocol - log("cannot get iframe.contentWindow document: " + err); - } + var result = readResponse(doc, life.xhr, s, retry); - if (doc) { - // successful getting content - return doc; - } + if (result) { + life.settle(result); + } + } - try { - // simply checking may throw in ie8 under ssl or mismatched protocol - doc = frame.contentDocument ? frame.contentDocument : frame.document; - } catch (err) { - // last attempt - log("cannot get iframe.contentDocument: " + err); - doc = frame.document; - } + // An exception while posting settles the upload with "error" and the exception. + function post() { + if (life.done()) { + // aborted before the delayed post + return; + } - return doc; + try { + doSubmit(); + } catch (err) { + log("upload failed: ", err); + life.fail(err); } + } - // Rails CSRF hack (thanks to Yvan Barthelemy); like jquery-ujs, only for the page's origin and - // only when the form is posted, since a get form would put the token in the url - var csrf_token = $("meta[name=csrf-token]").attr("content"); - var csrf_param = $("meta[name=csrf-param]").attr("content"); - var posts = !method || /post/i.test(method) || /post/i.test($form.attr2("method")); + if (s.forceSync) { + post(); + } else { + setTimeout(post, 10); // this lets dom updates render + } - if (csrf_param && csrf_token && posts && isSameOrigin(s.url)) { - s.extraData = s.extraData || {}; - s.extraData[csrf_param] = csrf_token; - } + return life.deferred; + } - function setFormAttribute(name, value) { - plainForm.setAttribute.call(form, name, value); - } + return function sendIframe(submission) { + var jqxhr; - // take a breath so that pending repaints get some cpu time before the upload starts - function doSubmit() { - // make sure form attrs are set - var t = $form.attr2("target"), - a = $form.attr2("action"), - mp = "multipart/form-data", - et = $form.attr("enctype") || $form.attr("encoding") || mp; - - // update form attrs in IE friendly way - setFormAttribute("target", id); - if (!method || /post/i.test(method)) { - setFormAttribute("method", "POST"); - } - if (a !== s.url) { - setFormAttribute("action", s.url); - } + // now, while the controls are still listed: ajaxSubmit clears the list when it returns, + // before a closeKeepAlive request completes + enableControls(submission.controls); - // ie borks in some cases when setting encoding - if (!s.skipEncodingOverride && (!method || /post/i.test(method))) { - setFormAttribute("encoding", mp); - setFormAttribute("enctype", mp); - } + // hack to fix Safari hang (thanks to Tim Molendijk for this) + // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d + if (submission.options.closeKeepAlive) { + deprecate("closeKeepAlive", "closeKeepAlive works around a Safari 3/4 bug and is deprecated"); + $.get(submission.options.closeKeepAlive, function () { + jqxhr = fileUploadIframe(submission); + }); + } else { + jqxhr = fileUploadIframe(submission); + } - // support timout - if (s.timeout) { - timeoutHandle = setTimeout(function () { - cb(CLIENT_TIMEOUT_ABORT); - }, s.timeout); - } + return jqxhr; + }; +} - // look for server aborts - function checkState() { - try { - var state = getDoc(io).readyState; +// A Submission is one ajaxSubmit call once its vetoes have passed: +// { form, $form, fields, controls, options, method, traditional }. `options` is the object the +// callbacks and events receive; later steps change it in place. - log("state = " + state); - if (state && state.toLowerCase() === "uninitialized") { - setTimeout(checkState, 50); - } - } catch (e) { - log("Server abort: ", e, " (", e.name, ")"); - cb(SERVER_ABORT); - if (timeoutHandle) { - clearTimeout(timeoutHandle); - } - timeoutHandle = undefined; - } - } +/** + * The submission steps. `feature` holds what the entry detected at load (fileapi, formdata), and + * `forms` reads form attributes and attr2-style properties (attribute, property), and + * `serialization` collects the form's fields and controls. + */ +function createSubmission(feature, forms, serialization) { + var $ = jQuery; - // add "extra" data to form if provided in options - var extraInputs = []; + function refuse(message) { + log(message); - // Builds the input with DOM properties: a name is never parsed as HTML. - function addHiddenInput(name, value) { - var input = ownerDocument.createElement("input"); + return null; + } - input.type = "hidden"; - input.name = name; - extraInputs.push($(input).val(value).appendTo(form)[0]); - } + // The options merged over the form's action, the method, and the ajax defaults. + function withDefaults(form, options, method) { + var action = options.url || forms.property(form, "action"); + var url = typeof action === "string" ? action.trim() : ""; - try { - if (s.extraData) { - for (var n in s.extraData) { - if (hasOwn.call(s.extraData, n)) { - // if using the $.param format that allows for multiple values with the same name - if ( - $.isPlainObject(s.extraData[n]) && - hasOwn.call(s.extraData[n], "name") && - hasOwn.call(s.extraData[n], "value") - ) { - addHiddenInput(s.extraData[n].name, s.extraData[n].value); - } else { - // arrays and objects become one field per value, as $.param sends them (#597) - var single = {}; - - single[n] = s.extraData[n]; - var fields = deepSerialize(single); - - for (var f = 0; f < fields.length; f++) { - addHiddenInput(fields[f][0], fields[f][1]); - } - } - } - } - } + // clean url (don't include hash value); an action that is only a fragment means this page + url = url.split("#")[0] || window.location.href.split("#")[0]; + // IE requires javascript:false in https, but this breaks chrome >83 and goes against spec. + // Instead of using javascript:false always, let's only apply it for IE. + var isMsie = /(MSIE|Trident)/.test(navigator.userAgent || ""); + var iframeSrc = isMsie && /^https/i.test(document.URL) ? "javascript:false" : "about:blank"; // eslint-disable-line no-script-url - if (!s.iframeTarget) { - // add iframe to doc and submit the form - $io.appendTo($body); - } + var merged = $.extend( + true, + { + url: url, + success: $.ajaxSettings.success, + type: method || $.ajaxSettings.type, + iframeSrc: iframeSrc, + }, + options + ); - if (io.attachEvent) { - io.attachEvent("onload", cb); - } else { - io.addEventListener("load", cb, false); - } + return keepContext(merged, [options]); + } + + /** + * The one method every transport sends, read after the hooks: `method` wins over `type`, and + * `type` is set to it. Undefined when only the ajax default applies, so each transport keeps + * its own default. + */ + function resolveMethod(options, defaultType) { + var resolved = options.method || options.type; - setTimeout(checkState, 15); + options.type = resolved; - try { - form.submit(); - } catch (err) { - // just in case form has element with name/id of 'submit' - plainForm.submit.call(form); - } - } finally { - // reset attrs and remove "extra" input elements - if (typeof a === "string") { - setFormAttribute("action", a); - } else { - // a control named action hid a missing action attribute - plainForm.removeAttribute.call(form, "action"); - } - setFormAttribute("enctype", et); // #380 - if (t) { - setFormAttribute("target", t); - } else { - plainForm.removeAttribute.call(form, "target"); - } - $(extraInputs).remove(); - } + return resolved === defaultType && !options.method ? undefined : resolved; + } + + // The data option, kept as extraData and encoded, or undefined without one. + function extraQuery(fields, options, traditional) { + if (!options.data) { + return undefined; + } + + var optionsData = typeof options.data === "function" ? options.data(fields) : options.data; + + if (typeof optionsData === "string") { + if (options.requestFormat === "json") { + throw new Error( + 'jquery.form: requestFormat "json" needs object data; a string data option is a query string' + ); } - if (s.forceSync) { - doSubmit(); + // a query string: sent as-is when urlencoded, as its own fields otherwise + options.extraData = queryPairs(optionsData); + + return optionsData; + } + + options.extraData = optionsData; + + return $.param(optionsData, traditional); + } + + // Sets a key as an own data property, so a name like __proto__ is an ordinary key. + function defineKey(object, key, value) { + Object.defineProperty(object, key, { + value: value, + enumerable: true, + writable: true, + configurable: true, + }); + } + + /** + * requestFormat "json" (#545): the fields as an object (a repeated name gives an array), merged + * with object data, sent as a JSON body. Based on the idea in PR #557 by zhangciwu. + */ + function jsonBody(options, fields) { + if (/^get$/i.test(options.type)) { + throw new Error('jquery.form: requestFormat "json" needs a method with a body, such as POST'); + } + + var body = {}; + var own = Object.prototype.hasOwnProperty; + + for (var i = 0; i < fields.length; i++) { + var name = fields[i].name; + + if (!own.call(body, name)) { + defineKey(body, name, fields[i].value); + } else if (Array.isArray(body[name])) { + body[name].push(fields[i].value); } else { - setTimeout(doSubmit, 10); // this lets dom updates render + defineKey(body, name, [body[name], fields[i].value]); + } + } + + var extra = options.extraData; + + for (var key in extra) { + if (own.call(extra, key)) { + defineKey(body, key, extra[key]); } + } + + options.data = JSON.stringify(body); + options.contentType = "application/json; charset=UTF-8"; + } + + // The fields of a query string, as the { name, value } list $.param takes. + function queryPairs(query) { + var pairs = []; + var parts = query.split("&"); + + for (var i = 0; i < parts.length; i++) { + if (parts[i]) { + var at = parts[i].indexOf("="); + var name = at < 0 ? parts[i] : parts[i].slice(0, at); + var value = at < 0 ? "" : parts[i].slice(at + 1); + + pairs.push({ name: decodeQuery(name), value: decodeQuery(value) }); + } + } + + return pairs; + } + + function decodeQuery(text) { + return decodeURIComponent(text.replace(/\+/g, " ")); + } + + // Puts the encoded fields in the url for a get, and in the data otherwise. + function encode(options, q, qx) { + if (qx) { + q = q ? q + "&" + qx : qx; + } + + if (options.type.toUpperCase() === "GET") { + // the query goes before any fragment in the url option + var hashAt = options.url.indexOf("#"); + var base = hashAt < 0 ? options.url : options.url.slice(0, hashAt); + + options.url = + base + (base.indexOf("?") >= 0 ? "&" : "?") + q + options.url.slice(base.length); + options.data = null; // data is null for 'get' + } else { + options.data = q; // data is the query string for 'post' + } + } + + // A callback option as a list: an array as given, one function, or none. + function callbackList(callback) { + if (Array.isArray(callback)) { + return callback; + } + + return callback ? [callback] : []; + } + + // Calls each callback in order with the same this and arguments. + function callEach(callbacks, context, args) { + for (var i = 0; i < callbacks.length; i++) { + callbacks[i].apply(context, args); + } + } + + /** + * Resolves the options, serializes the form, and runs the vetoes: the Submission, or null when + * an event or callback stopped it. + */ + function prepare($set, options) { + $set.each(function () { + assertRealParent(this); + }); + + var form = $set[0]; + var method = options.method || options.type || forms.property(form, "method"); + + options = withDefaults(form, options, method); + + // the ajax default type, when neither the caller nor the form gave a method + var defaultType = method ? undefined : options.type; + + // hook for manipulating the form data before it is extracted; + // convenient for use with rich editors like tinyMCE or FCKEditor + var veto = {}; + + $set.trigger("form-pre-serialize", [$set, options, veto]); + if (veto.veto) { + return refuse("ajaxSubmit: submit vetoed via form-pre-serialize trigger"); + } + + // provide opportunity to alter form data before it is serialized + if (options.beforeSerialize && options.beforeSerialize($set, options) === false) { + return refuse("ajaxSubmit: submit aborted via beforeSerialize callback"); + } + + var traditional = options.traditional; + + if (typeof traditional === "undefined") { + traditional = $.ajaxSettings.traditional; + } + + var collected = serialization.collect($set[0], options.semantic, options.filtering); + var fields = collected.fields; + var controls = collected.controls; + var qx = extraQuery(fields, options, traditional); + + // give pre-submit callback an opportunity to abort the submit + if (options.beforeSubmit && options.beforeSubmit(fields, $set, options) === false) { + return refuse("ajaxSubmit: submit aborted via beforeSubmit callback"); + } + + // fire vetoable 'validate' event + $set.trigger("form-submit-validate", [fields, $set, options, veto]); + if (veto.veto) { + return refuse("ajaxSubmit: submit vetoed via form-submit-validate trigger"); + } + + method = resolveMethod(options, defaultType); + + if (options.requestFormat === "json") { + jsonBody(options, fields); + } else { + encode(options, $.param(urlencodedFields(fields), traditional), qx); + } + + return { + form: form, + $form: $set, + fields: fields, + controls: controls, + options: options, + method: method, + traditional: traditional, + }; + } + + /** + * Wraps success, error and complete (a function or an array of them, as $.ajax takes) so each + * also receives the form, and adds the resetForm, + * clearForm and target steps before the success callbacks. + */ + function deliver(submission) { + var $set = submission.$form; + var options = submission.options; + var callbacks = []; + + if (options.resetForm) { + callbacks.push(function () { + $set.resetForm(); + }); + } + + if (options.clearForm) { + callbacks.push(function () { + $set.clearForm(options.includeHidden); + }); + } - var data, - doc, - domCheckCount = 50; + // perform a load on the target only if dataType is not provided + if (!options.dataType && options.target) { + var successes = callbackList(options.success); - function cb(e) { - if (xhr.aborted || callbackProcessed) { - return; - } + callbacks.push(function (data, textStatus, jqXHR) { + var successArguments = arguments, + fn = options.replaceTarget ? "replaceWith" : "html", + $target = $(options.target); - doc = getDoc(io); - if (!doc) { - log("cannot access response document"); - e = SERVER_ABORT; + // Only a string response is inserted. jQuery has already parsed a JSON or XML response, + // and inserting it would parse each of its strings as HTML. + if (typeof data === "string") { + $target[fn](data); + } else { + log("target: the response was parsed by jQuery, so it is not inserted"); } - if (e === CLIENT_TIMEOUT_ABORT && xhr) { - abortUpload("timeout", [xhr, "timeout"]); - return; + if (!$target.length) { + // nothing to fill: success still runs once, with the normal context + callEach(successes, this, successArguments); } - if (e === SERVER_ABORT && xhr) { - abortUpload("server abort", [xhr, "error", "server abort"]); - return; - } + $target.each(function () { + callEach(successes, this, successArguments); + }); + }); + } else { + $.merge(callbacks, callbackList(options.success)); + } - if (doc.location.href === s.iframeSrc) { - // response not received yet - return; - } + options.success = function (data, status, xhr) { + // jQuery 1.4+ passes xhr as 3rd arg + var context = options.context || this; // jQuery 1.4+ supports scope context - if (io.detachEvent) { - io.detachEvent("onload", cb); - } else { - io.removeEventListener("load", cb, false); - } + for (var i = 0, max = callbacks.length; i < max; i++) { + callbacks[i].apply(context, [data, status, xhr || $set, $set]); + } + }; - var status = "success", - errMsg; + if (options.error) { + var errors = callbackList(options.error); - try { - var isXml = s.dataType === "xml" || doc.XMLDocument || $.isXMLDoc(doc); + options.error = function (xhr, status, error) { + callEach(errors, options.context || this, [xhr, status, error, $set]); + }; + } - log("isXml=" + isXml); + if (options.complete) { + var completes = callbackList(options.complete); - if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) { - if (--domCheckCount) { - // in some browsers (Opera) the iframe DOM is not always traversable when - // the onload callback fires, so we loop a bit to accommodate - log("requeing onLoad callback, DOM not available"); - setTimeout(cb, 250); + options.complete = function (xhr, status) { + callEach(completes, options.context || this, [xhr, status, $set]); + }; + } + } - return; - } - // let this fall through because server response could be an empty document - // log('Could not access iframe DOM after mutiple tries.'); - // throw 'DOMException: not available'; - } + /** + * The transport for a submission: "iframe" for files without the File API or when forced, + * "formdata" for files with it, "ajax" otherwise. + */ + function chooseTransport(submission) { + var $set = submission.$form; + var options = submission.options; - // log('response detected'); - var docRoot = doc.body ? doc.body : doc.documentElement; + // [value] (issue #113), also see comment: + // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219 + // and the file inputs outside the form that belong to it through their form attribute + var fileInputs = $("input[type=file]:enabled", $set) + .add($(submission.controls).filter("input[type=file]")) + .filter(function () { + return $(this).val() !== ""; + }); + var hasFileInputs = fileInputs.length > 0; + // compared as the browser does: ASCII case-insensitive, without surrounding whitespace + var mp = /^[\t\n\f\r ]*multipart\/form-data[\t\n\f\r ]*$/i; + var multipart = + mp.test(forms.attribute($set[0], "enctype")) || mp.test(forms.attribute($set[0], "encoding")); + var fileAPI = feature.fileapi && feature.formdata; - xhr.responseText = docRoot ? docRoot.innerHTML : null; - xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; - if (isXml) { - s.dataType = "xml"; - } - xhr.getResponseHeader = function (header) { - var headers = { "content-type": s.dataType }; - - return headers[header.toLowerCase()]; - }; - // support for XHR 'status' & 'statusText' emulation : - if (docRoot) { - xhr.status = Number(docRoot.getAttribute("status")) || xhr.status; - xhr.statusText = docRoot.getAttribute("statusText") || xhr.statusText; - } + log("fileAPI :" + fileAPI); - var dt = (s.dataType || "").toLowerCase(); - var scr = /(json|script|text)/.test(dt); - - if (scr || s.textarea) { - // see if user embedded response in textarea - var ta = doc.getElementsByTagName("textarea")[0]; - - if (ta) { - xhr.responseText = ta.value; - // support for XHR 'status' & 'statusText' emulation : - xhr.status = Number(ta.getAttribute("status")) || xhr.status; - xhr.statusText = ta.getAttribute("statusText") || xhr.statusText; - } else if (scr) { - // account for browsers injecting pre around json response - var pre = doc.getElementsByTagName("pre")[0]; - var b = doc.getElementsByTagName("body")[0]; - - if (pre) { - xhr.responseText = pre.textContent ? pre.textContent : pre.innerText; - } else if (b) { - xhr.responseText = b.textContent ? b.textContent : b.innerText; - } - } - } + var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI; - try { - data = httpData(xhr, dt, s); // eslint-disable-line no-use-before-define - } catch (err) { - status = "parsererror"; - xhr.error = errMsg = err || status; - } - } catch (err) { - log("error caught: ", err); - status = "error"; - xhr.error = errMsg = err; - } + var transport = (hasFileInputs || multipart) && fileAPI ? "formdata" : "ajax"; - if (xhr.aborted) { - // abort() completed the upload while its response was processed - log("upload aborted"); + // options.iframe allows user to force iframe mode + // 06-NOV-09: now defaulting to iframe mode if file input is detected + if (options.iframe !== false && (options.iframe || shouldUseFrame)) { + transport = "iframe"; + } - return; - } + if (transport === "iframe" && !options.iframe) { + deprecate( + "iframe", + "choosing the iframe transport automatically without FormData is deprecated, set iframe: true" + ); + } - // an emulated HTTP error status wins, as in $.ajax; a parse error is kept otherwise - if (xhr.status && !((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)) { - status = "error"; - } + if (transport !== "ajax" && options.requestFormat === "json") { + throw new Error( + 'jquery.form: requestFormat "json" cannot send files or use the iframe transport' + ); + } - callbackProcessed = true; + return transport; + } - // ordering of these callbacks/triggers is odd, but that's how $.ajax does it - if (status === "success") { - s.success.call(s.context, data, "success", xhr); + return { prepare: prepare, deliver: deliver, chooseTransport: chooseTransport }; +} - deferred.resolve(xhr.responseText, "success", xhr); +(function ($) { - if (g) { - $.event.trigger("ajaxSuccess", [xhr, s]); - } - } else { - if (typeof errMsg === "undefined") { - errMsg = xhr.statusText; - } - if (s.error) { - s.error.call(s.context, xhr, status, errMsg); - } - deferred.reject(xhr, "error", errMsg); - if (g) { - $.event.trigger("ajaxError", [xhr, s, errMsg]); - } - } + /* + Usage Note: + ----------- + Do not use both ajaxSubmit and ajaxForm on the same form. These + functions are mutually exclusive. Use ajaxSubmit if you want + to bind your own submit handler to the form. For example, - complete(status); - } + $(document).ready(function() { + $('#myForm').on('submit', function(e) { + e.preventDefault(); // <-- important + $(this).ajaxSubmit({ + target: '#output' + }); + }); + }); - var httpData = function (xhr, type, s) { - // mostly lifted from jq1.4.4 + Use ajaxForm when you want the plugin to manage all the event binding + for you. For example, - var ct = xhr.getResponseHeader("content-type") || "", - xml = (type === "xml" || !type) && ct.indexOf("xml") >= 0, - data = xml ? xhr.responseXML : xhr.responseText; + $(document).ready(function() { + $('#myForm').ajaxForm({ + target: '#output' + }); + }); - if (xml && data.documentElement.nodeName === "parsererror") { - if ($.error) { - $.error("parsererror"); - } - } - if (s && s.dataFilter) { - data = s.dataFilter(data, type); - } - if (typeof data === "string") { - if ((type === "json" || !type) && ct.indexOf("json") >= 0) { - data = JSON.parse(data); - } else if (type === "script") { - $.globalEval(data); - } - } + You can also use ajaxForm with delegation (requires jQuery v1.7+), so the + form does not have to exist when you invoke ajaxForm: - return data; - }; + $('#myForm').ajaxForm({ + delegation: true, + target: '#output' + }); - return deferred; - } - }; + When using ajaxForm, the ajaxSubmit function will be invoked for you + at the appropriate time. + */ /** - * ajaxForm() provides a mechanism for fully automating form submission. - * - * The advantages of using this method instead of ajaxSubmit() are: - * - * 1: This method will include coordinates for elements (if the element - * is used to submit the form). - * 2. This method will include the submit element's name/value data (for the element that was - * used to submit the form). - * 3. This method binds the submit() method to the form for you. - * - * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely - * passes the options argument along after properly binding events for submit elements and - * the form itself. + * Feature detection */ - $.fn.ajaxForm = function (options, data, dataType, onSuccess) { - if (typeof options === "string" || (options === false && arguments.length > 0)) { - options = { - url: options, - data: data, - dataType: dataType, - }; - - if (typeof onSuccess === "function") { - options.success = onSuccess; - } - } + var feature = {}; - options = options || {}; - options.delegation = options.delegation && typeof $.fn.on === "function"; + feature.fileapi = $('').get(0).files !== undefined; + feature.formdata = typeof window.FormData !== "undefined"; - // in jQuery 1.3+ we can fix mistakes with the ready state - if (!options.delegation && this.length === 0) { - var o = { s: this.selector, c: this.context }; + var hasProp = !!$.fn.prop; + // What attr2 returns for a form: the property when it is a string, otherwise the attribute. The + // property is read plainly on purpose: a control named like it shadows it, and then the raw + // attribute is used. + function formProperty(form, name) { + var value = hasProp ? form[name] : undefined; - if (!$.isReady && o.s) { - log("DOM not ready, queuing ajaxForm"); - $(function () { - $(o.s, o.c).ajaxForm(options); - }); + return typeof value === "string" ? value : formAttribute(form, name); + } - return this; - } + var forms = { attribute: formAttribute, property: formProperty }; + var serialization = createSuccessfulControls(feature); + var steps = createSubmission(feature, forms, serialization); + var transports = { + iframe: createIframeTransport(hasProp, forms), + formdata: sendFormData, + ajax: sendAjax, + }; - // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() - log("terminating; zero elements found by selector" + ($.isReady ? "" : " (DOM not ready)")); + // attr2 uses prop when it can but checks the return type for + // an expected string. This accounts for the case where a form + // contains inputs with names like "action" or "method"; in those + // cases "prop" returns the element + $.fn.attr2 = function () { + deprecate("attr2", "attr2 is deprecated, use .prop() or .attr()"); - return this; + if (!hasProp) { + return this.attr.apply(this, arguments); } - if (options.delegation) { - $(document) - .off("submit.form-plugin", this.selector, doAjaxSubmit) - .off("click.form-plugin", this.selector, captureSubmittingElement) - .on("submit.form-plugin", this.selector, options, doAjaxSubmit) - .on("click.form-plugin", this.selector, options, captureSubmittingElement); - - return this; - } + var val = this.prop.apply(this, arguments); - if (options.beforeFormUnbind) { - options.beforeFormUnbind(this, options); + if ((val && val.jquery) || typeof val === "string") { + return val; } - return this.ajaxFormUnbind() - .on("submit.form-plugin", options, doAjaxSubmit) - .on("click.form-plugin", options, captureSubmittingElement); + return this.attr.apply(this, arguments); }; - // private event handlers - function doAjaxSubmit(e) { - /* jshint validthis:true */ - var options = e.data; + /** + * ajaxSubmit() provides a mechanism for immediately submitting + * an HTML form using AJAX. + * + * @param {object|string} options jquery.form.js parameters or custom url for submission + * @param {object} data extraData + * @param {string} dataType ajax dataType + * @param {function} onSuccess ajax success callback function + */ + $.fn.ajaxSubmit = function (options, data, dataType, onSuccess) { + deprecateOldJQuery($.fn.jquery); - if (!e.isDefaultPrevented()) { - // if event has been canceled, don't proceed - e.preventDefault(); - $(e.target).closest("form").ajaxSubmit(options); // #365 - } - } + // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) + if (!this.length) { + log("ajaxSubmit: skipping submit process - no element selected"); - function captureSubmittingElement(e) { - /* jshint validthis:true */ - // the clicked control, or the button around the clicked content (ex: a span within a button) - var $el = $(e.target).closest("button,input"); - var target = $el[0]; + return this; + } - // the type property, unlike the attribute, is "submit" for a button without a type (#588) - if (!target || (target.type !== "submit" && target.type !== "image")) { - return; + // #541: jQuery's slim build has no $.ajax + if (!$.ajax) { + throw new Error( + "jquery.form: ajaxSubmit needs the full jQuery build; this jQuery has no $.ajax" + ); } - var form = target.form; + var submission = steps.prepare(this, submitOptions(options, data, dataType, onSuccess)); - if (!form) { - // a submit control that belongs to no form - return; + if (!submission) { + return this; } - form.clk = target; + steps.deliver(submission); - if (target.type === "image") { - if (typeof e.offsetX !== "undefined") { - form.clk_x = e.offsetX; - form.clk_y = e.offsetY; - } else if (typeof $.fn.offset === "function") { - var offset = $el.offset(); + var jqxhr = transports[steps.chooseTransport(submission)](submission); - form.clk_x = e.pageX - offset.left; - form.clk_y = e.pageY - offset.top; - } else { - form.clk_x = e.pageX - target.offsetLeft; - form.clk_y = e.pageY - target.offsetTop; - } + this.removeData("jqxhr").data("jqxhr", jqxhr); + + // clear element array + for (var k = 0; k < submission.controls.length; k++) { + submission.controls[k] = null; } - // clear form vars - setTimeout(function () { - form.clk = form.clk_x = form.clk_y = null; - }, 100); - } - // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm - $.fn.ajaxFormUnbind = function () { - return this.off("submit.form-plugin click.form-plugin"); + // fire 'notify' event + this.trigger("form-submit-notify", [this, submission.options]); + + return this; }; + $.fn.ajaxForm = ajaxForm; + $.fn.ajaxFormUnbind = ajaxFormUnbind; + /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. @@ -1169,109 +2349,13 @@ * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function (semantic, elements, filtering) { - var a = []; - - if (this.length === 0) { - return a; - } - - var form = this[0]; - var formId = this.attr("id"); - var els = - semantic || typeof form.elements === "undefined" - ? form.getElementsByTagName("*") - : formElements(form); - var els2; - - if (els) { - els = $.makeArray(els); // convert to standard array - } - - // #386; account for inputs outside the form which use the 'form' attribute - // FinesseRus: in non-IE browsers outside fields are already included in form.elements. - if (formId && (semantic || /(Edge|Trident)\//.test(navigator.userAgent))) { - // hat tip @thet; the id is compared, never built into a selector - els2 = $(":input[form]") - .filter(function () { - return this.getAttribute("form") === formId; - }) - .get(); - if (els2.length) { - els = els.concat(els2); - } - } - - if (!els || !els.length) { - return a; - } + var collected = serialization.collect(this[0], semantic, filtering); - if (typeof filtering === "function") { - els = $.map(els, filtering); - } - - var i, j, n, v, el, max, jmax; - - for (i = 0, max = els.length; i < max; i++) { - el = els[i]; - n = el.name; - if (!n || el.disabled) { - continue; - } - - if (semantic && form.clk && el.type === "image") { - // handle image inputs on the fly when semantic == true - if (form.clk === el) { - a.push({ name: n, value: $(el).val(), type: el.type }); - a.push({ name: n + ".x", value: form.clk_x }, { name: n + ".y", value: form.clk_y }); - } - continue; - } - - v = $.fieldValue(el, true); - if (v && v.constructor === Array) { - if (elements) { - elements.push(el); - } - for (j = 0, jmax = v.length; j < jmax; j++) { - a.push({ name: n, value: v[j] }); - } - } else if (feature.fileapi && el.type === "file") { - if (elements) { - elements.push(el); - } - - var files = el.files; - - if (files.length) { - for (j = 0; j < files.length; j++) { - a.push({ name: n, value: files[j], type: el.type }); - } - } else { - // #180 - a.push({ name: n, value: "", type: el.type }); - } - } else if (v !== null && typeof v !== "undefined") { - if (elements) { - elements.push(el); - } - a.push({ name: n, value: v, type: el.type, required: el.required }); - } + if (elements) { + elements.push.apply(elements, collected.controls); } - if (!semantic && form.clk) { - // input type=='image' are not found in elements array! handle it here - var $input = $(form.clk), - input = $input[0]; - - n = input.name; - - if (n && !input.disabled && input.type === "image") { - a.push({ name: n, value: $input.val() }); - a.push({ name: n + ".x", value: form.clk_x }, { name: n + ".y", value: form.clk_y }); - } - } - - return a; + return collected.fields; }; /** @@ -1280,7 +2364,7 @@ */ $.fn.formSerialize = function (semantic) { // hand off to jQuery.param for proper encoding - return $.param(this.formToArray(semantic)); + return $.param(urlencodedFields(this.formToArray(semantic))); }; /** @@ -1293,7 +2377,8 @@ this.each(function () { var n = this.name; - if (!n) { + // a form is not a field, though it may have a name + if (!n || tagName(this) === "form") { return; } @@ -1373,65 +2458,13 @@ * Returns the value of the field element. */ $.fieldValue = function (el, successful) { - var n = el.name, - t = el.type, - tag = tagName(el); - - if (typeof successful === "undefined") { - successful = true; - } - - if ( - successful && - (!n || - el.disabled || - t === "reset" || - t === "button" || - ((t === "checkbox" || t === "radio") && !el.checked) || - ((t === "submit" || t === "image") && el.form && el.form.clk !== el) || - (tag === "select" && el.selectedIndex === -1)) - ) { - return null; - } + var required = typeof successful === "undefined" || successful; - if (tag === "select") { - var index = el.selectedIndex; - - if (index < 0) { - return null; - } - - var a = [], - ops = el.options; - var one = t === "select-one"; - var max = one ? index + 1 : ops.length; - - for (var i = one ? index : 0; i < max; i++) { - var op = ops[i]; - - if (op.selected && !op.disabled) { - var v = op.value; - - if (!v) { - // extra pain for IE... - v = - op.attributes && op.attributes.value && !op.attributes.value.specified - ? op.text - : op.value; - } - - if (one) { - return v; - } - - a.push(v); - } - } - - return a; + if (required && !isSuccessful(el, submitterElement(el.form))) { + return null; } - return $(el).val().replace(rCRLF, "\r\n"); + return valueOf(el); }; /** @@ -1451,9 +2484,15 @@ /** * Clears the selected form elements. */ - $.fn.clearFields = $.fn.clearInputs = function (includeHidden) { + $.fn.clearInputs = function (includeHidden) { + deprecate("clearInputs", "clearInputs is deprecated, use clearFields"); + + return this.clearFields(includeHidden); + }; + + $.fn.clearFields = function (includeHidden) { var re = - /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list + /^(?:color|date|datetime|datetime-local|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list return this.each(function () { var t = this.type, @@ -1504,7 +2543,16 @@ switch (tag) { case "input": this.checked = this.defaultChecked; - // fall through + + // as the native reset: types whose value is the value attribute keep it + if (this.type === "file") { + // a file input cannot take its value attribute; the native reset empties it + this.value = ""; + } else if (!/^(?:checkbox|radio|hidden|submit|reset|button|image)$/.test(this.type)) { + this.value = this.defaultValue; + } + + return true; case "textarea": this.value = this.defaultValue; @@ -1528,14 +2576,9 @@ return true; case "select": - // eslint-disable-next-line consistent-return -- jQuery .each() break semantics - el.find("option").each(function (i) { + // in order, as the native reset: of several default options, a single select keeps the last + el.find("option").each(function () { this.selected = this.defaultSelected; - if (this.defaultSelected && !el[0].multiple) { - el[0].selectedIndex = i; - - return false; - } }); return true; @@ -1550,14 +2593,8 @@ return true; case "form": - // guard against an input with the name of 'reset' - // note that IE reports the reset function as an 'object' - if ( - typeof this.reset === "function" || - (typeof this.reset === "object" && !this.reset.nodeType) - ) { - this.reset(); - } + // through the prototype: a control named reset shadows the method + callFormMethod(this, "reset"); return true; @@ -1611,20 +2648,5 @@ // expose debug var $.fn.ajaxSubmit.debug = false; - - // helper fn for console logging - function log() { - if (!$.fn.ajaxSubmit.debug) { - return; - } - - var msg = "[jquery.form] " + Array.prototype.join.call(arguments, ""); - - if (window.console && window.console.log) { - window.console.log(msg); - } else if (window.opera && window.opera.postError) { - window.opera.postError(msg); - } - } })(jQuery); })); diff --git a/dist/jquery.form.min.js b/dist/jquery.form.min.js index d0c6692..6a5c91c 100644 --- a/dist/jquery.form.min.js +++ b/dist/jquery.form.min.js @@ -1,6 +1,6 @@ /*! * jQuery Form Plugin - * version: 4.4.0 + * version: 4.5.0 * Requires jQuery v1.7.2 or later * Project repository: https://github.com/jquery-form/form @@ -19,5 +19,5 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ -!function(e){"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof module&&module.exports?module.exports=function(t,r){return void 0===r&&(r="undefined"!=typeof window?require("jquery"):require("jquery")(t)),e(r),r}:e(jQuery)}(function(e){!function(e){"use strict";var t=/\r?\n/g,r={};r.fileapi=void 0!==e('').get(0).files,r.formdata=void 0!==window.FormData;var a=!!e.fn.prop,n=Object.prototype.hasOwnProperty,o=document.createElement("form");function i(e){return"string"==typeof e.tagName?e.tagName.toLowerCase():""}function s(t){var r=t.data;t.isDefaultPrevented()||(t.preventDefault(),e(t.target).closest("form").ajaxSubmit(r))}function l(t){var r=e(t.target).closest("button,input"),a=r[0];if(a&&("submit"===a.type||"image"===a.type)){var n=a.form;if(n){if(n.clk=a,"image"===a.type)if(void 0!==t.offsetX)n.clk_x=t.offsetX,n.clk_y=t.offsetY;else if("function"==typeof e.fn.offset){var o=r.offset();n.clk_x=t.pageX-o.left,n.clk_y=t.pageY-o.top}else n.clk_x=t.pageX-a.offsetLeft,n.clk_y=t.pageY-a.offsetTop;setTimeout(function(){n.clk=n.clk_x=n.clk_y=null},100)}}}function c(){if(e.fn.ajaxSubmit.debug){var t="[jquery.form] "+Array.prototype.join.call(arguments,"");window.console&&window.console.log?window.console.log(t):window.opera&&window.opera.postError&&window.opera.postError(t)}}e.fn.attr2=function(){if(!a)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)},e.fn.ajaxSubmit=function(t,i,s,l){if(!this.length)return c("ajaxSubmit: skipping submit process - no element selected"),this;var u,f,d,p,m=this;"function"==typeof t?t={success:t}:"string"==typeof t||!1===t&&arguments.length>0?(t={url:t,data:i,dataType:s},"function"==typeof l&&(t.success=l)):void 0===t&&(t={}),u=t.method||t.type||this.attr2("method"),d=(d="string"==typeof(f=t.url||this.attr2("action"))?f.trim():"").split("#")[0]||window.location.href.split("#")[0],p=/(MSIE|Trident)/.test(navigator.userAgent||"")&&/^https/i.test(document.URL)?"javascript:false":"about:blank",t=e.extend(!0,{url:d,success:e.ajaxSettings.success,type:u||e.ajaxSettings.type,iframeSrc:p},t);var h={};if(this.trigger("form-pre-serialize",[this,t,h]),h.veto)return c("ajaxSubmit: submit vetoed via form-pre-serialize trigger"),this;if(t.beforeSerialize&&!1===t.beforeSerialize(this,t))return c("ajaxSubmit: submit aborted via beforeSerialize callback"),this;var v=t.traditional;void 0===v&&(v=e.ajaxSettings.traditional);var g,y=[],x=this.formToArray(t.semantic,y,t.filtering);if(t.data){var b="function"==typeof t.data?t.data(x):t.data;t.extraData=b,g=e.param(b,v)}if(t.beforeSubmit&&!1===t.beforeSubmit(x,this,t))return c("ajaxSubmit: submit aborted via beforeSubmit callback"),this;if(this.trigger("form-submit-validate",[x,this,t,h]),h.veto)return c("ajaxSubmit: submit vetoed via form-submit-validate trigger"),this;var T=e.param(x,v);if(g&&(T=T?T+"&"+g:g),"GET"===t.type.toUpperCase()){var j=t.url.indexOf("#"),S=j<0?t.url:t.url.slice(0,j);t.url=S+(S.indexOf("?")>=0?"&":"?")+T+t.url.slice(S.length),t.data=null}else t.data=T;var w=[];if(t.resetForm&&w.push(function(){m.resetForm()}),t.clearForm&&w.push(function(){m.clearForm(t.includeHidden)}),!t.dataType&&t.target){var k=t.success||function(){};w.push(function(r,a,n){var o=arguments,i=t.replaceTarget?"replaceWith":"html",s=e(t.target);"string"==typeof r?s[i](r):c("target: the response was parsed by jQuery, so it is not inserted"),s.each(function(){k.apply(this,o)})})}else t.success&&(Array.isArray(t.success)?e.merge(w,t.success):w.push(t.success));if(t.success=function(e,r,a){for(var n=t.context||this,o=0,i=w.length;o0,F="multipart/form-data",L=m.attr("enctype")===F||m.attr("encoding")===F,M=r.fileapi&&r.formdata;c("fileAPI :"+M);var O,C=(A||L)&&!M;!1!==t.iframe&&(t.iframe||C)?t.closeKeepAlive?e.get(t.closeKeepAlive,function(){O=X()}):O=X():O=(A||L)&&M?function(r){for(var a=new FormData,n=0;n=200&&v.status<300||304===v.status)&&(a="error"),T=!0,"success"===a?(l.success.call(l.context,q,"success",v),S.resolve(v.responseText,"success",v),f&&e.event.trigger("ajaxSuccess",[v,l])):(void 0===r&&(r=v.statusText),l.error&&l.error.call(l.context,v,a,r),S.reject(v,"error",r),f&&e.event.trigger("ajaxError",[v,l,r])),E(a))}}var N=function(t,r,a){var n=t.getResponseHeader("content-type")||"",o=("xml"===r||!r)&&n.indexOf("xml")>=0,i=o?t.responseXML:t.responseText;return o&&"parsererror"===i.documentElement.nodeName&&e.error&&e.error("parsererror"),a&&a.dataFilter&&(i=a.dataFilter(i,r)),"string"==typeof i&&(("json"===r||!r)&&n.indexOf("json")>=0?i=JSON.parse(i):"script"===r&&e.globalEval(i)),i};return S}},e.fn.ajaxForm=function(t,r,a,n){if(("string"==typeof t||!1===t&&arguments.length>0)&&(t={url:t,data:r,dataType:a},"function"==typeof n&&(t.success=n)),(t=t||{}).delegation=t.delegation&&"function"==typeof e.fn.on,!t.delegation&&0===this.length){var o={s:this.selector,c:this.context};return!e.isReady&&o.s?(c("DOM not ready, queuing ajaxForm"),e(function(){e(o.s,o.c).ajaxForm(t)}),this):(c("terminating; zero elements found by selector"+(e.isReady?"":" (DOM not ready)")),this)}return t.delegation?(e(document).off("submit.form-plugin",this.selector,s).off("click.form-plugin",this.selector,l).on("submit.form-plugin",this.selector,t,s).on("click.form-plugin",this.selector,t,l),this):(t.beforeFormUnbind&&t.beforeFormUnbind(this,t),this.ajaxFormUnbind().on("submit.form-plugin",t,s).on("click.form-plugin",t,l))},e.fn.ajaxFormUnbind=function(){return this.off("submit.form-plugin click.form-plugin")},e.fn.formToArray=function(t,a,n){var o=[];if(0===this.length)return o;var i,s,l,c,u,f,d,p,m=this[0],h=this.attr("id"),v=t||void 0===m.elements?m.getElementsByTagName("*"):function(e){var t=window.HTMLFormElement&&window.HTMLFormElement.prototype,r=t&&Object.getOwnPropertyDescriptor(t,"elements");try{return r.get.call(e)}catch(t){return e.elements}}(m);if(v&&(v=e.makeArray(v)),h&&(t||/(Edge|Trident)\//.test(navigator.userAgent))&&(i=e(":input[form]").filter(function(){return this.getAttribute("form")===h}).get()).length&&(v=v.concat(i)),!v||!v.length)return o;for("function"==typeof n&&(v=e.map(v,n)),s=0,d=v.length;s=0)return r;return null}var l="jqFormSubmitter";function f(e,t,r){try{e[t]=r}catch(e){}}function d(e,t){var r=e[t],n=a(e,"elements");return n&&r&&n.namedItem(t)===r?void 0:r}function p(t,r,n,a){e.data(t,l,{el:r,x:n,y:a}),f(t,"clk",r),"image"===r.type&&(f(t,"clk_x",n),f(t,"clk_y",a)),setTimeout(function(){e.data(t,l,null),f(t,"clk",null),f(t,"clk_x",null),f(t,"clk_y",null)},100)}function m(t){var r=c(t.target,["button","input"]);if(r&&("submit"===r.type||"image"===r.type)){var n=r.form;if(n){var a="image"===r.type?function(t,r){if(void 0!==t.offsetX)return[t.offsetX,t.offsetY];if("function"==typeof e.fn.offset){var n=e(r).offset();return[t.pageX-n.left,t.pageY-n.top]}return[t.pageX-r.offsetLeft,t.pageY-r.offsetTop]}(t,r):[];p(n,r,a[0],a[1])}}}function v(t){if(!t)return null;var r=e.data(t,l);if(r)return r;var n=d(t,"clk");return n?{el:n,x:d(t,"clk_x"),y:d(t,"clk_y")}:null}function h(){if(e.fn.ajaxSubmit.debug){var t="[jquery.form] "+Array.prototype.join.call(arguments,"");window.console&&window.console.log?window.console.log(t):window.opera&&window.opera.postError&&window.opera.postError(t)}}var g={};function y(t,r){e.fn.ajaxSubmit.debug&&!g[t]&&(g[t]=!0,window.console&&"function"==typeof window.console.warn&&window.console.warn("[jquery.form] "+r+" (removed in 5.0)"))}function b(e){(function(e){var t=String(e).split("."),r=Number(t[0]);return r<3||3===r&&Number(t[1])<5})(e)&&y("jquery","support for jQuery "+e+" is deprecated, 5.0 needs jQuery 3.5 or later")}function x(e,t,r,n){if("string"!=typeof e&&!1!==e)return e;var a={url:e,data:t,dataType:r};return"function"==typeof n&&(a.success=n),a}function j(e,t,r,n){return"function"==typeof e?{success:e}:void 0===(e=x(e,t,r,n))?{}:!1===e.url||""===e.url?function(e){var t={};for(var r in e)"url"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t}(e):e}function w(e,t){for(var r=0;r"'),e(function(){e(n.s,n.c).ajaxForm(r)}),t):(h("terminating; zero elements found by selector"+(e.isReady?"":" (DOM not ready)")),t)}(this,t))}function L(t){return"string"==typeof t?(D(t),this):(t!==A&&(q={},e(document).off("submit.form-plugin click.form-plugin")),this.off("submit.form-plugin click.form-plugin"))}function M(t,r){if(!u(t))return e(t).attr(r);var n=o(t,"getAttribute",r);return null===n?void 0:n}var N=/\r\n|\r|\n/g,C=/\r/g,I=/^(?:fieldset|object|output)$/;function $(e){return"function"==typeof e.matches?e.matches(":disabled"):!!e.disabled}function P(t){if("select"===i(t))return function(e){var t=e.selectedIndex;if(t<0)return null;for(var r=[],n=e.options,a="select-one"===e.type,o=a?t+1:n.length,i=a?t:0;i=0,o=a?e.responseXML:e.responseText;return a&&"parsererror"===o.documentElement.nodeName&&J.error&&J.error("parsererror"),r&&r.dataFilter&&(o=r.dataFilter(o,t)),"string"==typeof o&&(("json"===t||!t)&&n.indexOf("json")>=0?o=JSON.parse(o):"script"===t&&J.globalEval(o)),o}(t,s,r)}catch(e){i="parsererror",t.error=o=e||i}}catch(e){h("error caught: ",e),i="error",t.error=o=e}return{status:i,data:a,errMsg:o}}var re=e;function ne(e,t){var r,n,a,o=re.Deferred(),i={aborted:0,responseText:null,responseXML:null,status:0,statusText:"n/a",getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(e){s(e,[i,"aborted",e])}};function u(){return i.aborted||a}function s(n,a,s){var c=s||("timeout"===n?"timeout":"aborted");u()||(h("aborting upload... "+c),i.aborted=1,t.stop(),i.error=c,e.error&&e.error.call(e.context,i,c,n),o.reject.apply(o,a),r&&re.event.trigger("ajaxError",[i,e,c]),l(c))}function c(){r&&re.event.trigger("ajaxComplete",[i,e]),r&&! --re.active&&re.event.trigger("ajaxStop")}function l(r){e.complete&&e.complete.call(e.context,i,r),c(),clearTimeout(n),setTimeout(function(){t.release(),i.responseXML=null},100)}function f(t){var n=t.status,u=t.errMsg;if(i.aborted)h("upload aborted");else if(i.status&&!(i.status>=200&&i.status<300||304===i.status)&&(n="error"),a=!0,"success"!==n)void 0===u&&(u=i.statusText),e.error&&e.error.call(e.context,i,n,u),o.reject(i,"error",u),r&&re.event.trigger("ajaxError",[i,e,u]),l(n);else{var s=function(t){var n;try{e.success.call(e.context,t,"success",i)}catch(e){n={error:e}}return o.resolve(i.responseText,"success",i),r&&re.event.trigger("ajaxSuccess",[i,e,t]),n}(t.data);if(l(n),s)throw s.error}}return o.abort=function(e){i.abort(e)},{xhr:i,deferred:o,start:function(){return(r=e.global)&&0===re.active++&&re.event.trigger("ajaxStart"),e.beforeSend&&!1===e.beforeSend.call(e.context,i,e)?(u()||(a=!0,o.reject(),r&&re.event.trigger("ajaxError",[i,e,"canceled"]),c()),!1):!i.aborted&&(r&&re.event.trigger("ajaxSend",[i,e]),!i.aborted)},done:u,abort:s,settle:f,fail:function(e){f({status:"error",errMsg:e})},startTimer:function(t){e.timeout&&(n=setTimeout(t,e.timeout))},stopTimer:function(){clearTimeout(n),n=void 0}}}var ae=e;function oe(e,t){var r=0;function n(e){var n=e.form,i=e.method,u=w(ae.extend(!0,{},ae.ajaxSettings,e.options),[ae.ajaxSettings,e.options]);u.context=u.context||u;var s=a(n,"ownerDocument"),l=ae(c(n,["body"])),f=function(e,t,r){var n,a;if(e.iframeTarget)(a=(n=ae(e.iframeTarget,r)).attr("name"))?t=a:(n.attr("name",t),n.each(function(){!function(e,t){try{e.contentWindow&&(e.contentWindow.name=t)}catch(e){}}(this,t)}));else{var o=r.createElement("iframe");o.setAttribute("name",t),o.setAttribute("src",e.iframeSrc),(n=ae(o)).css({position:"absolute",top:"-1000px",left:"-1000px"})}return{$io:n,id:t}}(u,"jqFormIO"+(new Date).getTime()+r++,s),d=f.$io,p=d[0],m=ne(u,function(e,t){return{stop:function(){try{t[0].contentWindow.document.execCommand&&t[0].contentWindow.document.execCommand("Stop")}catch(e){}t.attr("src",e.iframeSrc)},release:function(){e.iframeTarget?t.attr("src",e.iframeSrc):t.remove()}}}(u,d)),v=50;if(!m.start())return m.deferred;function g(){try{var e=Z(p).readyState;h("state = "+e),e&&"uninitialized"===e.toLowerCase()&&setTimeout(g,50)}catch(e){h("Server abort: ",e," (",e.name,")"),x(2),m.stopTimer()}}function y(){var r=function(e){var t={};return Q.each(V,function(r,n){t[n]=o(e,"hasAttribute",n)?o(e,"getAttribute",n):null}),t}(n);!function(e,t,r,n,a){var o="multipart/form-data";G(e,"target",t),!r||/post/i.test(r)?G(e,"method","POST"):_(r)&&!_(a.property(e,"method"))&&G(e,"method","GET"),G(e,"action",n.url),n.skipEncodingOverride||r&&!/post/i.test(r)||(G(e,"encoding",o),G(e,"enctype",o))}(n,f.id,i,u,t),m.startTimer(function(){x(1)});var a=[];try{!function(e,t,r,n,a){function o(r,n){var o=t.createElement("input");o.type="hidden",o.name=r,a.push(Q(o).val(n).appendTo(e)[0])}if(r)for(var i in r)if(B.call(r,i))if(Q.isPlainObject(r[i])&&B.call(r[i],"name")&&B.call(r[i],"value"))o(r[i].name,r[i].value);else{var u={};u[i]=r[i];for(var s=U(u,n),c=0;c=0?"&":"?")+t+e.url.slice(a.length),e.data=null}else e.data=t}(t,a.param(X(v),p),g),{form:c,$form:e,fields:v,controls:h,options:t,method:l,traditional:p}))},deliver:function(e){var t=e.$form,r=e.options,n=[];if(r.resetForm&&n.push(function(){t.resetForm()}),r.clearForm&&n.push(function(){t.clearForm(r.includeHidden)}),!r.dataType&&r.target){var o=l(r.success);n.push(function(e,t,n){var i=arguments,u=r.replaceTarget?"replaceWith":"html",s=a(r.target);"string"==typeof e?s[u](e):h("target: the response was parsed by jQuery, so it is not inserted"),s.length||f(o,this,i),s.each(function(){f(o,this,i)})})}else a.merge(n,l(r.success));if(r.success=function(e,a,o){for(var i=r.context||this,u=0,s=n.length;u0,u=/^[\t\n\f\r ]*multipart\/form-data[\t\n\f\r ]*$/i,s=u.test(r.attribute(n[0],"enctype"))||u.test(r.attribute(n[0],"encoding")),c=t.fileapi&&t.formdata;h("fileAPI :"+c);var l=(i||s)&&!c,f=(i||s)&&c?"formdata":"ajax";if(!1!==o.iframe&&(o.iframe||l)&&(f="iframe"),"iframe"!==f||o.iframe||y("iframe","choosing the iframe transport automatically without FormData is deprecated, set iframe: true"),"ajax"!==f&&"json"===o.requestFormat)throw new Error('jquery.form: requestFormat "json" cannot send files or use the iframe transport');return f}}}!function(e){var t={};t.fileapi=void 0!==e('').get(0).files,t.formdata=void 0!==window.FormData;var r=!!e.fn.prop;var n={attribute:M,property:function(e,t){var n=r?e[t]:void 0;return"string"==typeof n?n:M(e,t)}},a=R(t),u=ie(t,n,a),s={iframe:oe(r,n),formdata:z,ajax:W};e.fn.attr2=function(){if(y("attr2","attr2 is deprecated, use .prop() or .attr()"),!r)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)},e.fn.ajaxSubmit=function(t,r,n,a){if(b(e.fn.jquery),!this.length)return h("ajaxSubmit: skipping submit process - no element selected"),this;if(!e.ajax)throw new Error("jquery.form: ajaxSubmit needs the full jQuery build; this jQuery has no $.ajax");var o=u.prepare(this,j(t,r,n,a));if(!o)return this;u.deliver(o);var i=s[u.chooseTransport(o)](o);this.removeData("jqxhr").data("jqxhr",i);for(var c=0;c').get(0).files !== undefined;\n feature.formdata = typeof window.FormData !== \"undefined\";\n\n var hasProp = !!$.fn.prop;\n // Called through the prototype: an extraData key or a form field may be named hasOwnProperty.\n var hasOwn = Object.prototype.hasOwnProperty;\n\n // A control named like a form member (elements, setAttribute) shadows that member on the form,\n // so forms are read and changed through members a control cannot shadow.\n var plainForm = document.createElement(\"form\");\n\n // Resolves both URLs through anchors, as jQuery does for crossDomain, so IE's anchor quirks\n // apply to both sides of the comparison.\n function isSameOrigin(url) {\n var origin = document.createElement(\"a\");\n var target = document.createElement(\"a\");\n\n origin.href = window.location.href;\n target.href = url;\n // IE fills in the host of a relative URL only once the resolved href is assigned back\n target.href = target.href; // eslint-disable-line no-self-assign\n\n return origin.protocol + \"//\" + origin.host === target.protocol + \"//\" + target.host;\n }\n\n // Nodes such as the document and text nodes have no tag name (#600).\n function tagName(el) {\n return typeof el.tagName === \"string\" ? el.tagName.toLowerCase() : \"\";\n }\n\n function formElements(form) {\n var proto = window.HTMLFormElement && window.HTMLFormElement.prototype;\n var descriptor = proto && Object.getOwnPropertyDescriptor(proto, \"elements\");\n\n try {\n return descriptor.get.call(form);\n } catch (e) {\n // no DOM prototype accessors, or another element with controls such as a fieldset\n return form.elements;\n }\n }\n\n // attr2 uses prop when it can but checks the return type for\n // an expected string. This accounts for the case where a form\n // contains inputs with names like \"action\" or \"method\"; in those\n // cases \"prop\" returns the element\n $.fn.attr2 = function () {\n if (!hasProp) {\n return this.attr.apply(this, arguments);\n }\n\n var val = this.prop.apply(this, arguments);\n\n if ((val && val.jquery) || typeof val === \"string\") {\n return val;\n }\n\n return this.attr.apply(this, arguments);\n };\n\n /**\n * ajaxSubmit() provides a mechanism for immediately submitting\n * an HTML form using AJAX.\n *\n * @param\t{object|string}\toptions\t\tjquery.form.js parameters or custom url for submission\n * @param\t{object}\t\tdata\t\textraData\n * @param\t{string}\t\tdataType\tajax dataType\n * @param\t{function}\t\tonSuccess\tajax success callback function\n */\n $.fn.ajaxSubmit = function (options, data, dataType, onSuccess) {\n // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)\n if (!this.length) {\n log(\"ajaxSubmit: skipping submit process - no element selected\");\n\n return this;\n }\n\n var method,\n action,\n url,\n isMsie,\n iframeSrc,\n $form = this;\n\n if (typeof options === \"function\") {\n options = { success: options };\n } else if (typeof options === \"string\" || (options === false && arguments.length > 0)) {\n options = {\n url: options,\n data: data,\n dataType: dataType,\n };\n\n if (typeof onSuccess === \"function\") {\n options.success = onSuccess;\n }\n } else if (typeof options === \"undefined\") {\n options = {};\n }\n\n method = options.method || options.type || this.attr2(\"method\");\n action = options.url || this.attr2(\"action\");\n\n url = typeof action === \"string\" ? action.trim() : \"\";\n // clean url (don't include hash value); an action that is only a fragment means this page\n url = url.split(\"#\")[0] || window.location.href.split(\"#\")[0];\n // IE requires javascript:false in https, but this breaks chrome >83 and goes against spec.\n // Instead of using javascript:false always, let's only apply it for IE.\n isMsie = /(MSIE|Trident)/.test(navigator.userAgent || \"\");\n iframeSrc = isMsie && /^https/i.test(document.URL) ? \"javascript:false\" : \"about:blank\"; // eslint-disable-line no-script-url\n\n options = $.extend(\n true,\n {\n url: url,\n success: $.ajaxSettings.success,\n type: method || $.ajaxSettings.type,\n iframeSrc: iframeSrc,\n },\n options\n );\n\n // hook for manipulating the form data before it is extracted;\n // convenient for use with rich editors like tinyMCE or FCKEditor\n var veto = {};\n\n this.trigger(\"form-pre-serialize\", [this, options, veto]);\n\n if (veto.veto) {\n log(\"ajaxSubmit: submit vetoed via form-pre-serialize trigger\");\n\n return this;\n }\n\n // provide opportunity to alter form data before it is serialized\n if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {\n log(\"ajaxSubmit: submit aborted via beforeSerialize callback\");\n\n return this;\n }\n\n var traditional = options.traditional;\n\n if (typeof traditional === \"undefined\") {\n traditional = $.ajaxSettings.traditional;\n }\n\n var elements = [];\n var qx,\n a = this.formToArray(options.semantic, elements, options.filtering);\n\n if (options.data) {\n var optionsData = typeof options.data === \"function\" ? options.data(a) : options.data;\n\n options.extraData = optionsData;\n qx = $.param(optionsData, traditional);\n }\n\n // give pre-submit callback an opportunity to abort the submit\n if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {\n log(\"ajaxSubmit: submit aborted via beforeSubmit callback\");\n\n return this;\n }\n\n // fire vetoable 'validate' event\n this.trigger(\"form-submit-validate\", [a, this, options, veto]);\n if (veto.veto) {\n log(\"ajaxSubmit: submit vetoed via form-submit-validate trigger\");\n\n return this;\n }\n\n var q = $.param(a, traditional);\n\n if (qx) {\n q = q ? q + \"&\" + qx : qx;\n }\n\n if (options.type.toUpperCase() === \"GET\") {\n // the query goes before any fragment in the url option\n var hashAt = options.url.indexOf(\"#\");\n var base = hashAt < 0 ? options.url : options.url.slice(0, hashAt);\n\n options.url =\n base + (base.indexOf(\"?\") >= 0 ? \"&\" : \"?\") + q + options.url.slice(base.length);\n options.data = null; // data is null for 'get'\n } else {\n options.data = q; // data is the query string for 'post'\n }\n\n var callbacks = [];\n\n if (options.resetForm) {\n callbacks.push(function () {\n $form.resetForm();\n });\n }\n\n if (options.clearForm) {\n callbacks.push(function () {\n $form.clearForm(options.includeHidden);\n });\n }\n\n // perform a load on the target only if dataType is not provided\n if (!options.dataType && options.target) {\n var oldSuccess = options.success || function () {};\n\n callbacks.push(function (data, textStatus, jqXHR) {\n var successArguments = arguments,\n fn = options.replaceTarget ? \"replaceWith\" : \"html\",\n $target = $(options.target);\n\n // Only a string response is inserted. jQuery has already parsed a JSON or XML response,\n // and inserting it would parse each of its strings as HTML.\n if (typeof data === \"string\") {\n $target[fn](data);\n } else {\n log(\"target: the response was parsed by jQuery, so it is not inserted\");\n }\n\n $target.each(function () {\n oldSuccess.apply(this, successArguments);\n });\n });\n } else if (options.success) {\n if (Array.isArray(options.success)) {\n $.merge(callbacks, options.success);\n } else {\n callbacks.push(options.success);\n }\n }\n\n options.success = function (data, status, xhr) {\n // jQuery 1.4+ passes xhr as 3rd arg\n var context = options.context || this; // jQuery 1.4+ supports scope context\n\n for (var i = 0, max = callbacks.length; i < max; i++) {\n callbacks[i].apply(context, [data, status, xhr || $form, $form]);\n }\n };\n\n if (options.error) {\n var oldError = options.error;\n\n options.error = function (xhr, status, error) {\n var context = options.context || this;\n\n oldError.apply(context, [xhr, status, error, $form]);\n };\n }\n\n if (options.complete) {\n var oldComplete = options.complete;\n\n options.complete = function (xhr, status) {\n var context = options.context || this;\n\n oldComplete.apply(context, [xhr, status, $form]);\n };\n }\n\n // are there files to upload?\n\n // [value] (issue #113), also see comment:\n // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219\n var fileInputs = $(\"input[type=file]:enabled\", this).filter(function () {\n return $(this).val() !== \"\";\n });\n var hasFileInputs = fileInputs.length > 0;\n var mp = \"multipart/form-data\";\n var multipart = $form.attr(\"enctype\") === mp || $form.attr(\"encoding\") === mp;\n var fileAPI = feature.fileapi && feature.formdata;\n\n log(\"fileAPI :\" + fileAPI);\n\n var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;\n var jqxhr;\n\n // options.iframe allows user to force iframe mode\n // 06-NOV-09: now defaulting to iframe mode if file input is detected\n if (options.iframe !== false && (options.iframe || shouldUseFrame)) {\n // hack to fix Safari hang (thanks to Tim Molendijk for this)\n // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d\n if (options.closeKeepAlive) {\n $.get(options.closeKeepAlive, function () {\n jqxhr = fileUploadIframe(a);\n });\n } else {\n jqxhr = fileUploadIframe(a);\n }\n } else if ((hasFileInputs || multipart) && fileAPI) {\n jqxhr = fileUploadXhr(a);\n } else {\n jqxhr = $.ajax(options);\n }\n\n $form.removeData(\"jqxhr\").data(\"jqxhr\", jqxhr);\n\n // clear element array\n for (var k = 0; k < elements.length; k++) {\n elements[k] = null;\n }\n\n // fire 'notify' event\n this.trigger(\"form-submit-notify\", [this, options]);\n\n return this;\n\n // utility fn for deep serialization\n function deepSerialize(extraData) {\n var param = $.param(extraData, traditional);\n var serialized = param ? param.split(\"&\") : [];\n var len = serialized.length;\n var result = [];\n var i, part;\n\n for (i = 0; i < len; i++) {\n // #252; undo param space replacement\n serialized[i] = serialized[i].replace(/\\+/g, \" \");\n part = serialized[i].split(\"=\");\n // #278; use array instead of object storage, favoring array serializations\n result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]);\n }\n\n return result;\n }\n\n // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)\n function fileUploadXhr(a) {\n var formdata = new FormData();\n\n for (var i = 0; i < a.length; i++) {\n formdata.append(a[i].name, a[i].value);\n }\n\n if (options.extraData) {\n var serializedData = deepSerialize(options.extraData);\n\n for (i = 0; i < serializedData.length; i++) {\n formdata.append(serializedData[i][0], serializedData[i][1]);\n }\n }\n\n options.data = null;\n\n var s = $.extend(true, {}, $.ajaxSettings, options, {\n contentType: false,\n processData: false,\n cache: false,\n type: method || \"POST\",\n });\n\n if (options.uploadProgress) {\n // workaround because jqXHR does not expose upload property\n s.xhr = function () {\n var xhr = $.ajaxSettings.xhr();\n\n if (xhr.upload) {\n xhr.upload.addEventListener(\n \"progress\",\n function (event) {\n var percent = 0;\n var position = event.loaded || event.position; /* event.position is deprecated */\n var total = event.total;\n\n if (event.lengthComputable) {\n percent = Math.ceil((position / total) * 100);\n }\n\n options.uploadProgress(event, position, total, percent);\n },\n false\n );\n }\n\n return xhr;\n };\n }\n\n s.data = null;\n\n var beforeSend = s.beforeSend;\n\n s.beforeSend = function (xhr, o) {\n // Send FormData() provided by user\n if (options.formData) {\n o.data = options.formData;\n } else {\n o.data = formdata;\n }\n\n if (beforeSend) {\n beforeSend.call(this, xhr, o);\n }\n };\n\n return $.ajax(s);\n }\n\n // private function for handling file uploads (hat tip to YAHOO!)\n function fileUploadIframe(a) {\n var form = $form[0],\n el,\n i,\n s,\n g,\n id,\n $io,\n io,\n xhr,\n sub,\n n,\n timeoutHandle,\n callbackProcessed;\n var deferred = $.Deferred();\n\n // #341\n deferred.abort = function (status) {\n xhr.abort(status);\n };\n\n // ensure that every serialized input is still enabled\n for (i = 0; i < elements.length; i++) {\n el = $(elements[i]);\n if (hasProp) {\n el.prop(\"disabled\", false);\n } else {\n el.removeAttr(\"disabled\");\n }\n }\n\n s = $.extend(true, {}, $.ajaxSettings, options);\n s.context = s.context || s;\n id = \"jqFormIO\" + new Date().getTime();\n var ownerDocument = form.ownerDocument;\n var $body = $form.closest(\"body\");\n\n if (s.iframeTarget) {\n $io = $(s.iframeTarget, ownerDocument);\n n = $io.attr2(\"name\");\n if (!n) {\n $io.attr2(\"name\", id);\n } else {\n id = n;\n }\n } else {\n io = ownerDocument.createElement(\"iframe\");\n io.setAttribute(\"name\", id);\n io.setAttribute(\"src\", s.iframeSrc);\n $io = $(io);\n $io.css({ position: \"absolute\", top: \"-1000px\", left: \"-1000px\" });\n }\n io = $io[0];\n\n xhr = {\n // mock object\n aborted: 0,\n responseText: null,\n responseXML: null,\n status: 0,\n statusText: \"n/a\",\n getAllResponseHeaders: function () {},\n getResponseHeader: function () {},\n setRequestHeader: function () {},\n abort: function (status) {\n abortUpload(status, [xhr, \"aborted\", status]);\n },\n };\n\n // Completes an aborted upload once and rejects the Deferred with `rejection`.\n function abortUpload(status, rejection) {\n var e = status === \"timeout\" ? \"timeout\" : \"aborted\";\n\n if (xhr.aborted || callbackProcessed) {\n return;\n }\n\n log(\"aborting upload... \" + e);\n xhr.aborted = 1;\n\n try {\n // #214, #257\n if (io.contentWindow.document.execCommand) {\n io.contentWindow.document.execCommand(\"Stop\");\n }\n } catch (ignore) {}\n\n $io.attr(\"src\", s.iframeSrc); // abort op in progress\n xhr.error = e;\n if (s.error) {\n s.error.call(s.context, xhr, e, status);\n }\n deferred.reject.apply(deferred, rejection);\n\n if (g) {\n $.event.trigger(\"ajaxError\", [xhr, s, e]);\n }\n\n complete(e);\n }\n\n // The steps every finished or aborted upload ends with, in $.ajax order.\n function complete(status) {\n if (g) {\n $.event.trigger(\"ajaxComplete\", [xhr, s]);\n }\n\n if (g && !--$.active) {\n $.event.trigger(\"ajaxStop\");\n }\n\n if (s.complete) {\n s.complete.call(s.context, xhr, status);\n }\n\n if (s.timeout) {\n clearTimeout(timeoutHandle);\n }\n\n // clean up\n setTimeout(function () {\n if (!s.iframeTarget) {\n $io.remove();\n } else {\n // adding else to clean up existing iframe response.\n $io.attr(\"src\", s.iframeSrc);\n }\n xhr.responseXML = null;\n }, 100);\n }\n\n g = s.global;\n // trigger ajax global events so that activity/block indicators work like normal\n if (g && $.active++ === 0) {\n $.event.trigger(\"ajaxStart\");\n }\n if (g) {\n $.event.trigger(\"ajaxSend\", [xhr, s]);\n }\n\n if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {\n if (s.global) {\n $.active--;\n }\n deferred.reject();\n\n return deferred;\n }\n\n if (xhr.aborted) {\n // abort() in beforeSend already rejected the Deferred\n return deferred;\n }\n\n // add submitting element to data if we know it\n sub = form.clk;\n if (sub) {\n n = sub.name;\n if (n && !sub.disabled) {\n s.extraData = s.extraData || {};\n s.extraData[n] = sub.value;\n if (sub.type === \"image\") {\n s.extraData[n + \".x\"] = form.clk_x;\n s.extraData[n + \".y\"] = form.clk_y;\n }\n }\n }\n\n var CLIENT_TIMEOUT_ABORT = 1;\n var SERVER_ABORT = 2;\n\n function getDoc(frame) {\n /* it looks like contentWindow or contentDocument do not\n * carry the protocol property in ie8, when running under ssl\n * frame.document is the only valid response document, since\n * the protocol is know but not on the other two objects. strange?\n * \"Same origin policy\" http://en.wikipedia.org/wiki/Same_origin_policy\n */\n\n var doc = null;\n\n // IE8 cascading access check\n try {\n if (frame.contentWindow) {\n doc = frame.contentWindow.document;\n }\n } catch (err) {\n // IE8 access denied under ssl & missing protocol\n log(\"cannot get iframe.contentWindow document: \" + err);\n }\n\n if (doc) {\n // successful getting content\n return doc;\n }\n\n try {\n // simply checking may throw in ie8 under ssl or mismatched protocol\n doc = frame.contentDocument ? frame.contentDocument : frame.document;\n } catch (err) {\n // last attempt\n log(\"cannot get iframe.contentDocument: \" + err);\n doc = frame.document;\n }\n\n return doc;\n }\n\n // Rails CSRF hack (thanks to Yvan Barthelemy); like jquery-ujs, only for the page's origin and\n // only when the form is posted, since a get form would put the token in the url\n var csrf_token = $(\"meta[name=csrf-token]\").attr(\"content\");\n var csrf_param = $(\"meta[name=csrf-param]\").attr(\"content\");\n var posts = !method || /post/i.test(method) || /post/i.test($form.attr2(\"method\"));\n\n if (csrf_param && csrf_token && posts && isSameOrigin(s.url)) {\n s.extraData = s.extraData || {};\n s.extraData[csrf_param] = csrf_token;\n }\n\n function setFormAttribute(name, value) {\n plainForm.setAttribute.call(form, name, value);\n }\n\n // take a breath so that pending repaints get some cpu time before the upload starts\n function doSubmit() {\n // make sure form attrs are set\n var t = $form.attr2(\"target\"),\n a = $form.attr2(\"action\"),\n mp = \"multipart/form-data\",\n et = $form.attr(\"enctype\") || $form.attr(\"encoding\") || mp;\n\n // update form attrs in IE friendly way\n setFormAttribute(\"target\", id);\n if (!method || /post/i.test(method)) {\n setFormAttribute(\"method\", \"POST\");\n }\n if (a !== s.url) {\n setFormAttribute(\"action\", s.url);\n }\n\n // ie borks in some cases when setting encoding\n if (!s.skipEncodingOverride && (!method || /post/i.test(method))) {\n setFormAttribute(\"encoding\", mp);\n setFormAttribute(\"enctype\", mp);\n }\n\n // support timout\n if (s.timeout) {\n timeoutHandle = setTimeout(function () {\n cb(CLIENT_TIMEOUT_ABORT);\n }, s.timeout);\n }\n\n // look for server aborts\n function checkState() {\n try {\n var state = getDoc(io).readyState;\n\n log(\"state = \" + state);\n if (state && state.toLowerCase() === \"uninitialized\") {\n setTimeout(checkState, 50);\n }\n } catch (e) {\n log(\"Server abort: \", e, \" (\", e.name, \")\");\n cb(SERVER_ABORT);\n if (timeoutHandle) {\n clearTimeout(timeoutHandle);\n }\n timeoutHandle = undefined;\n }\n }\n\n // add \"extra\" data to form if provided in options\n var extraInputs = [];\n\n // Builds the input with DOM properties: a name is never parsed as HTML.\n function addHiddenInput(name, value) {\n var input = ownerDocument.createElement(\"input\");\n\n input.type = \"hidden\";\n input.name = name;\n extraInputs.push($(input).val(value).appendTo(form)[0]);\n }\n\n try {\n if (s.extraData) {\n for (var n in s.extraData) {\n if (hasOwn.call(s.extraData, n)) {\n // if using the $.param format that allows for multiple values with the same name\n if (\n $.isPlainObject(s.extraData[n]) &&\n hasOwn.call(s.extraData[n], \"name\") &&\n hasOwn.call(s.extraData[n], \"value\")\n ) {\n addHiddenInput(s.extraData[n].name, s.extraData[n].value);\n } else {\n // arrays and objects become one field per value, as $.param sends them (#597)\n var single = {};\n\n single[n] = s.extraData[n];\n var fields = deepSerialize(single);\n\n for (var f = 0; f < fields.length; f++) {\n addHiddenInput(fields[f][0], fields[f][1]);\n }\n }\n }\n }\n }\n\n if (!s.iframeTarget) {\n // add iframe to doc and submit the form\n $io.appendTo($body);\n }\n\n if (io.attachEvent) {\n io.attachEvent(\"onload\", cb);\n } else {\n io.addEventListener(\"load\", cb, false);\n }\n\n setTimeout(checkState, 15);\n\n try {\n form.submit();\n } catch (err) {\n // just in case form has element with name/id of 'submit'\n plainForm.submit.call(form);\n }\n } finally {\n // reset attrs and remove \"extra\" input elements\n if (typeof a === \"string\") {\n setFormAttribute(\"action\", a);\n } else {\n // a control named action hid a missing action attribute\n plainForm.removeAttribute.call(form, \"action\");\n }\n setFormAttribute(\"enctype\", et); // #380\n if (t) {\n setFormAttribute(\"target\", t);\n } else {\n plainForm.removeAttribute.call(form, \"target\");\n }\n $(extraInputs).remove();\n }\n }\n\n if (s.forceSync) {\n doSubmit();\n } else {\n setTimeout(doSubmit, 10); // this lets dom updates render\n }\n\n var data,\n doc,\n domCheckCount = 50;\n\n function cb(e) {\n if (xhr.aborted || callbackProcessed) {\n return;\n }\n\n doc = getDoc(io);\n if (!doc) {\n log(\"cannot access response document\");\n e = SERVER_ABORT;\n }\n if (e === CLIENT_TIMEOUT_ABORT && xhr) {\n abortUpload(\"timeout\", [xhr, \"timeout\"]);\n\n return;\n }\n if (e === SERVER_ABORT && xhr) {\n abortUpload(\"server abort\", [xhr, \"error\", \"server abort\"]);\n\n return;\n }\n\n if (doc.location.href === s.iframeSrc) {\n // response not received yet\n return;\n }\n\n if (io.detachEvent) {\n io.detachEvent(\"onload\", cb);\n } else {\n io.removeEventListener(\"load\", cb, false);\n }\n\n var status = \"success\",\n errMsg;\n\n try {\n var isXml = s.dataType === \"xml\" || doc.XMLDocument || $.isXMLDoc(doc);\n\n log(\"isXml=\" + isXml);\n\n if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) {\n if (--domCheckCount) {\n // in some browsers (Opera) the iframe DOM is not always traversable when\n // the onload callback fires, so we loop a bit to accommodate\n log(\"requeing onLoad callback, DOM not available\");\n setTimeout(cb, 250);\n\n return;\n }\n // let this fall through because server response could be an empty document\n // log('Could not access iframe DOM after mutiple tries.');\n // throw 'DOMException: not available';\n }\n\n // log('response detected');\n var docRoot = doc.body ? doc.body : doc.documentElement;\n\n xhr.responseText = docRoot ? docRoot.innerHTML : null;\n xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;\n if (isXml) {\n s.dataType = \"xml\";\n }\n xhr.getResponseHeader = function (header) {\n var headers = { \"content-type\": s.dataType };\n\n return headers[header.toLowerCase()];\n };\n // support for XHR 'status' & 'statusText' emulation :\n if (docRoot) {\n xhr.status = Number(docRoot.getAttribute(\"status\")) || xhr.status;\n xhr.statusText = docRoot.getAttribute(\"statusText\") || xhr.statusText;\n }\n\n var dt = (s.dataType || \"\").toLowerCase();\n var scr = /(json|script|text)/.test(dt);\n\n if (scr || s.textarea) {\n // see if user embedded response in textarea\n var ta = doc.getElementsByTagName(\"textarea\")[0];\n\n if (ta) {\n xhr.responseText = ta.value;\n // support for XHR 'status' & 'statusText' emulation :\n xhr.status = Number(ta.getAttribute(\"status\")) || xhr.status;\n xhr.statusText = ta.getAttribute(\"statusText\") || xhr.statusText;\n } else if (scr) {\n // account for browsers injecting pre around json response\n var pre = doc.getElementsByTagName(\"pre\")[0];\n var b = doc.getElementsByTagName(\"body\")[0];\n\n if (pre) {\n xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;\n } else if (b) {\n xhr.responseText = b.textContent ? b.textContent : b.innerText;\n }\n }\n }\n\n try {\n data = httpData(xhr, dt, s); // eslint-disable-line no-use-before-define\n } catch (err) {\n status = \"parsererror\";\n xhr.error = errMsg = err || status;\n }\n } catch (err) {\n log(\"error caught: \", err);\n status = \"error\";\n xhr.error = errMsg = err;\n }\n\n if (xhr.aborted) {\n // abort() completed the upload while its response was processed\n log(\"upload aborted\");\n\n return;\n }\n\n // an emulated HTTP error status wins, as in $.ajax; a parse error is kept otherwise\n if (xhr.status && !((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)) {\n status = \"error\";\n }\n\n callbackProcessed = true;\n\n // ordering of these callbacks/triggers is odd, but that's how $.ajax does it\n if (status === \"success\") {\n s.success.call(s.context, data, \"success\", xhr);\n\n deferred.resolve(xhr.responseText, \"success\", xhr);\n\n if (g) {\n $.event.trigger(\"ajaxSuccess\", [xhr, s]);\n }\n } else {\n if (typeof errMsg === \"undefined\") {\n errMsg = xhr.statusText;\n }\n if (s.error) {\n s.error.call(s.context, xhr, status, errMsg);\n }\n deferred.reject(xhr, \"error\", errMsg);\n if (g) {\n $.event.trigger(\"ajaxError\", [xhr, s, errMsg]);\n }\n }\n\n complete(status);\n }\n\n var httpData = function (xhr, type, s) {\n // mostly lifted from jq1.4.4\n\n var ct = xhr.getResponseHeader(\"content-type\") || \"\",\n xml = (type === \"xml\" || !type) && ct.indexOf(\"xml\") >= 0,\n data = xml ? xhr.responseXML : xhr.responseText;\n\n if (xml && data.documentElement.nodeName === \"parsererror\") {\n if ($.error) {\n $.error(\"parsererror\");\n }\n }\n if (s && s.dataFilter) {\n data = s.dataFilter(data, type);\n }\n if (typeof data === \"string\") {\n if ((type === \"json\" || !type) && ct.indexOf(\"json\") >= 0) {\n data = JSON.parse(data);\n } else if (type === \"script\") {\n $.globalEval(data);\n }\n }\n\n return data;\n };\n\n return deferred;\n }\n };\n\n /**\n * ajaxForm() provides a mechanism for fully automating form submission.\n *\n * The advantages of using this method instead of ajaxSubmit() are:\n *\n * 1: This method will include coordinates for elements (if the element\n *\tis used to submit the form).\n * 2. This method will include the submit element's name/value data (for the element that was\n *\tused to submit the form).\n * 3. This method binds the submit() method to the form for you.\n *\n * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely\n * passes the options argument along after properly binding events for submit elements and\n * the form itself.\n */\n $.fn.ajaxForm = function (options, data, dataType, onSuccess) {\n if (typeof options === \"string\" || (options === false && arguments.length > 0)) {\n options = {\n url: options,\n data: data,\n dataType: dataType,\n };\n\n if (typeof onSuccess === \"function\") {\n options.success = onSuccess;\n }\n }\n\n options = options || {};\n options.delegation = options.delegation && typeof $.fn.on === \"function\";\n\n // in jQuery 1.3+ we can fix mistakes with the ready state\n if (!options.delegation && this.length === 0) {\n var o = { s: this.selector, c: this.context };\n\n if (!$.isReady && o.s) {\n log(\"DOM not ready, queuing ajaxForm\");\n $(function () {\n $(o.s, o.c).ajaxForm(options);\n });\n\n return this;\n }\n\n // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()\n log(\"terminating; zero elements found by selector\" + ($.isReady ? \"\" : \" (DOM not ready)\"));\n\n return this;\n }\n\n if (options.delegation) {\n $(document)\n .off(\"submit.form-plugin\", this.selector, doAjaxSubmit)\n .off(\"click.form-plugin\", this.selector, captureSubmittingElement)\n .on(\"submit.form-plugin\", this.selector, options, doAjaxSubmit)\n .on(\"click.form-plugin\", this.selector, options, captureSubmittingElement);\n\n return this;\n }\n\n if (options.beforeFormUnbind) {\n options.beforeFormUnbind(this, options);\n }\n\n return this.ajaxFormUnbind()\n .on(\"submit.form-plugin\", options, doAjaxSubmit)\n .on(\"click.form-plugin\", options, captureSubmittingElement);\n };\n\n // private event handlers\n function doAjaxSubmit(e) {\n /* jshint validthis:true */\n var options = e.data;\n\n if (!e.isDefaultPrevented()) {\n // if event has been canceled, don't proceed\n e.preventDefault();\n $(e.target).closest(\"form\").ajaxSubmit(options); // #365\n }\n }\n\n function captureSubmittingElement(e) {\n /* jshint validthis:true */\n // the clicked control, or the button around the clicked content (ex: a span within a button)\n var $el = $(e.target).closest(\"button,input\");\n var target = $el[0];\n\n // the type property, unlike the attribute, is \"submit\" for a button without a type (#588)\n if (!target || (target.type !== \"submit\" && target.type !== \"image\")) {\n return;\n }\n\n var form = target.form;\n\n if (!form) {\n // a submit control that belongs to no form\n return;\n }\n\n form.clk = target;\n\n if (target.type === \"image\") {\n if (typeof e.offsetX !== \"undefined\") {\n form.clk_x = e.offsetX;\n form.clk_y = e.offsetY;\n } else if (typeof $.fn.offset === \"function\") {\n var offset = $el.offset();\n\n form.clk_x = e.pageX - offset.left;\n form.clk_y = e.pageY - offset.top;\n } else {\n form.clk_x = e.pageX - target.offsetLeft;\n form.clk_y = e.pageY - target.offsetTop;\n }\n }\n // clear form vars\n setTimeout(function () {\n form.clk = form.clk_x = form.clk_y = null;\n }, 100);\n }\n\n // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm\n $.fn.ajaxFormUnbind = function () {\n return this.off(\"submit.form-plugin click.form-plugin\");\n };\n\n /**\n * formToArray() gathers form element data into an array of objects that can\n * be passed to any of the following ajax functions: $.get, $.post, or load.\n * Each object in the array has both a 'name' and 'value' property. An example of\n * an array for a simple login form might be:\n *\n * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]\n *\n * It is this array that is passed to pre-submit callback functions provided to the\n * ajaxSubmit() and ajaxForm() methods.\n */\n $.fn.formToArray = function (semantic, elements, filtering) {\n var a = [];\n\n if (this.length === 0) {\n return a;\n }\n\n var form = this[0];\n var formId = this.attr(\"id\");\n var els =\n semantic || typeof form.elements === \"undefined\"\n ? form.getElementsByTagName(\"*\")\n : formElements(form);\n var els2;\n\n if (els) {\n els = $.makeArray(els); // convert to standard array\n }\n\n // #386; account for inputs outside the form which use the 'form' attribute\n // FinesseRus: in non-IE browsers outside fields are already included in form.elements.\n if (formId && (semantic || /(Edge|Trident)\\//.test(navigator.userAgent))) {\n // hat tip @thet; the id is compared, never built into a selector\n els2 = $(\":input[form]\")\n .filter(function () {\n return this.getAttribute(\"form\") === formId;\n })\n .get();\n if (els2.length) {\n els = els.concat(els2);\n }\n }\n\n if (!els || !els.length) {\n return a;\n }\n\n if (typeof filtering === \"function\") {\n els = $.map(els, filtering);\n }\n\n var i, j, n, v, el, max, jmax;\n\n for (i = 0, max = els.length; i < max; i++) {\n el = els[i];\n n = el.name;\n if (!n || el.disabled) {\n continue;\n }\n\n if (semantic && form.clk && el.type === \"image\") {\n // handle image inputs on the fly when semantic == true\n if (form.clk === el) {\n a.push({ name: n, value: $(el).val(), type: el.type });\n a.push({ name: n + \".x\", value: form.clk_x }, { name: n + \".y\", value: form.clk_y });\n }\n continue;\n }\n\n v = $.fieldValue(el, true);\n if (v && v.constructor === Array) {\n if (elements) {\n elements.push(el);\n }\n for (j = 0, jmax = v.length; j < jmax; j++) {\n a.push({ name: n, value: v[j] });\n }\n } else if (feature.fileapi && el.type === \"file\") {\n if (elements) {\n elements.push(el);\n }\n\n var files = el.files;\n\n if (files.length) {\n for (j = 0; j < files.length; j++) {\n a.push({ name: n, value: files[j], type: el.type });\n }\n } else {\n // #180\n a.push({ name: n, value: \"\", type: el.type });\n }\n } else if (v !== null && typeof v !== \"undefined\") {\n if (elements) {\n elements.push(el);\n }\n a.push({ name: n, value: v, type: el.type, required: el.required });\n }\n }\n\n if (!semantic && form.clk) {\n // input type=='image' are not found in elements array! handle it here\n var $input = $(form.clk),\n input = $input[0];\n\n n = input.name;\n\n if (n && !input.disabled && input.type === \"image\") {\n a.push({ name: n, value: $input.val() });\n a.push({ name: n + \".x\", value: form.clk_x }, { name: n + \".y\", value: form.clk_y });\n }\n }\n\n return a;\n };\n\n /**\n * Serializes form data into a 'submittable' string. This method will return a string\n * in the format: name1=value1&name2=value2\n */\n $.fn.formSerialize = function (semantic) {\n // hand off to jQuery.param for proper encoding\n return $.param(this.formToArray(semantic));\n };\n\n /**\n * Serializes all field elements in the jQuery object into a query string.\n * This method will return a string in the format: name1=value1&name2=value2\n */\n $.fn.fieldSerialize = function (successful) {\n var a = [];\n\n this.each(function () {\n var n = this.name;\n\n if (!n) {\n return;\n }\n\n var v = $.fieldValue(this, successful);\n\n if (v && v.constructor === Array) {\n for (var i = 0, max = v.length; i < max; i++) {\n a.push({ name: n, value: v[i] });\n }\n } else if (v !== null && typeof v !== \"undefined\") {\n a.push({ name: this.name, value: v });\n }\n });\n\n // hand off to jQuery.param for proper encoding\n return $.param(a);\n };\n\n /**\n * Returns the value(s) of the element in the matched set. For example, consider the following form:\n *\n *\t
\n *\t\t\n *\t\t\n *\t\t\n *\t\t\n *\t\t\n *\t\t\n *\t
\n *\n *\tvar v = $('input[type=text]').fieldValue();\n *\t// if no values are entered into the text inputs\n *\tv === ['','']\n *\t// if values entered into the text inputs are 'foo' and 'bar'\n *\tv === ['foo','bar']\n *\n *\tvar v = $('input[type=checkbox]').fieldValue();\n *\t// if neither checkbox is checked\n *\tv === undefined\n *\t// if both checkboxes are checked\n *\tv === ['B1', 'B2']\n *\n *\tvar v = $('input[type=radio]').fieldValue();\n *\t// if neither radio is checked\n *\tv === undefined\n *\t// if first radio is checked\n *\tv === ['C1']\n *\n * The successful argument controls whether or not the field element must be 'successful'\n * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).\n * The default value of the successful argument is true. If this value is false the value(s)\n * for each element is returned.\n *\n * Note: This method *always* returns an array. If no valid value can be determined the\n *\tarray will be empty, otherwise it will contain one or more values.\n */\n $.fn.fieldValue = function (successful) {\n for (var val = [], i = 0, max = this.length; i < max; i++) {\n var el = this[i];\n var v = $.fieldValue(el, successful);\n\n if (v === null || typeof v === \"undefined\" || (v.constructor === Array && !v.length)) {\n continue;\n }\n\n if (v.constructor === Array) {\n $.merge(val, v);\n } else {\n val.push(v);\n }\n }\n\n return val;\n };\n\n /**\n * Returns the value of the field element.\n */\n $.fieldValue = function (el, successful) {\n var n = el.name,\n t = el.type,\n tag = tagName(el);\n\n if (typeof successful === \"undefined\") {\n successful = true;\n }\n\n if (\n successful &&\n (!n ||\n el.disabled ||\n t === \"reset\" ||\n t === \"button\" ||\n ((t === \"checkbox\" || t === \"radio\") && !el.checked) ||\n ((t === \"submit\" || t === \"image\") && el.form && el.form.clk !== el) ||\n (tag === \"select\" && el.selectedIndex === -1))\n ) {\n return null;\n }\n\n if (tag === \"select\") {\n var index = el.selectedIndex;\n\n if (index < 0) {\n return null;\n }\n\n var a = [],\n ops = el.options;\n var one = t === \"select-one\";\n var max = one ? index + 1 : ops.length;\n\n for (var i = one ? index : 0; i < max; i++) {\n var op = ops[i];\n\n if (op.selected && !op.disabled) {\n var v = op.value;\n\n if (!v) {\n // extra pain for IE...\n v =\n op.attributes && op.attributes.value && !op.attributes.value.specified\n ? op.text\n : op.value;\n }\n\n if (one) {\n return v;\n }\n\n a.push(v);\n }\n }\n\n return a;\n }\n\n return $(el).val().replace(rCRLF, \"\\r\\n\");\n };\n\n /**\n * Clears the form data. Takes the following actions on the form's input fields:\n * - input text fields will have their 'value' property set to the empty string\n * - select elements will have their 'selectedIndex' property set to -1\n * - checkbox and radio inputs will have their 'checked' property set to false\n * - inputs of type submit, button, reset, and hidden will *not* be effected\n * - button elements will *not* be effected\n */\n $.fn.clearForm = function (includeHidden) {\n return this.each(function () {\n $(\"input,select,textarea\", this).clearFields(includeHidden);\n });\n };\n\n /**\n * Clears the selected form elements.\n */\n $.fn.clearFields = $.fn.clearInputs = function (includeHidden) {\n var re =\n /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list\n\n return this.each(function () {\n var t = this.type,\n tag = tagName(this);\n\n if (re.test(t) || tag === \"textarea\") {\n this.value = \"\";\n } else if (t === \"checkbox\" || t === \"radio\") {\n this.checked = false;\n } else if (tag === \"select\") {\n this.selectedIndex = -1;\n } else if (t === \"file\") {\n if (/MSIE/.test(navigator.userAgent)) {\n $(this).replaceWith($(this).clone(true));\n } else {\n $(this).val(\"\");\n }\n } else if (includeHidden) {\n // includeHidden can be the value true, or it can be a selector string\n // indicating a special test; for example:\n // $('#myForm').clearForm('.special:hidden')\n // the above would clean hidden inputs that have the class of 'special'\n if (\n (includeHidden === true && /hidden/.test(t)) ||\n (typeof includeHidden === \"string\" && $(this).is(includeHidden))\n ) {\n this.value = \"\";\n }\n }\n });\n };\n\n /**\n * Resets the form data or individual elements. Takes the following actions\n * on the selected tags:\n * - all fields within form elements will be reset to their original value\n * - input / textarea / select fields will be reset to their original value\n * - option / optgroup fields (for multi-selects) will defaulted individually\n * - non-multiple options will find the right select to default\n * - label elements will be searched against its 'for' attribute\n * - all others will be searched for appropriate children to default\n */\n $.fn.resetForm = function () {\n return this.each(function () {\n var el = $(this);\n var tag = tagName(this);\n\n switch (tag) {\n case \"input\":\n this.checked = this.defaultChecked;\n // fall through\n\n case \"textarea\":\n this.value = this.defaultValue;\n\n return true;\n\n case \"option\":\n case \"optgroup\":\n var select = el.parents(\"select\");\n\n if (select.length && select[0].multiple) {\n if (tag === \"option\") {\n this.selected = this.defaultSelected;\n } else {\n el.find(\"option\").resetForm();\n }\n } else {\n select.resetForm();\n }\n\n return true;\n\n case \"select\":\n // eslint-disable-next-line consistent-return -- jQuery .each() break semantics\n el.find(\"option\").each(function (i) {\n this.selected = this.defaultSelected;\n if (this.defaultSelected && !el[0].multiple) {\n el[0].selectedIndex = i;\n\n return false;\n }\n });\n\n return true;\n\n case \"label\":\n // The control whose id the for attribute names, and the controls inside the label. The\n // filter keeps a for that names an ancestor from resetting the label again.\n var forEl = this.htmlFor && this.ownerDocument.getElementById(this.htmlFor);\n\n el.find(\"input,select,textarea\").add(forEl).filter(\"input,select,textarea\").resetForm();\n\n return true;\n\n case \"form\":\n // guard against an input with the name of 'reset'\n // note that IE reports the reset function as an 'object'\n if (\n typeof this.reset === \"function\" ||\n (typeof this.reset === \"object\" && !this.reset.nodeType)\n ) {\n this.reset();\n }\n\n return true;\n\n default:\n el.find(\"form,input,label,select,textarea\").resetForm();\n\n return true;\n }\n });\n };\n\n /**\n * Enables or disables any matching elements.\n */\n $.fn.enable = function (b) {\n if (typeof b === \"undefined\") {\n b = true;\n }\n\n return this.each(function () {\n this.disabled = !b;\n });\n };\n\n /**\n * Checks/unchecks any matching checkboxes or radio buttons and\n * selects/deselects and matching option elements.\n */\n $.fn.selected = function (select) {\n if (typeof select === \"undefined\") {\n select = true;\n }\n\n return this.each(function () {\n var t = this.type;\n\n if (t === \"checkbox\" || t === \"radio\") {\n this.checked = select;\n } else if (tagName(this) === \"option\") {\n var $sel = $(this).parent(\"select\");\n\n if (select && $sel[0] && $sel[0].type === \"select-one\") {\n // deselect all other options\n $sel.find(\"option\").selected(false);\n }\n\n this.selected = select;\n }\n });\n };\n\n // expose debug var\n $.fn.ajaxSubmit.debug = false;\n\n // helper fn for console logging\n function log() {\n if (!$.fn.ajaxSubmit.debug) {\n return;\n }\n\n var msg = \"[jquery.form] \" + Array.prototype.join.call(arguments, \"\");\n\n if (window.console && window.console.log) {\n window.console.log(msg);\n } else if (window.opera && window.opera.postError) {\n window.opera.postError(msg);\n }\n }\n})(jQuery);\n\nexport default jQuery;\n"],"names":["$","rCRLF","feature","fileapi","undefined","get","files","formdata","window","FormData","hasProp","fn","prop","hasOwn","Object","prototype","hasOwnProperty","plainForm","document","createElement","tagName","el","toLowerCase","doAjaxSubmit","e","options","data","isDefaultPrevented","preventDefault","target","closest","ajaxSubmit","captureSubmittingElement","$el","type","form","clk","offsetX","clk_x","clk_y","offsetY","offset","pageX","left","pageY","top","offsetLeft","offsetTop","setTimeout","log","debug","msg","Array","join","call","arguments","console","opera","postError","attr2","this","attr","apply","val","jquery","dataType","onSuccess","length","method","action","url","iframeSrc","$form","success","trim","split","location","href","test","navigator","userAgent","URL","extend","ajaxSettings","veto","trigger","beforeSerialize","traditional","qx","elements","a","formToArray","semantic","filtering","optionsData","extraData","param","beforeSubmit","q","toUpperCase","hashAt","indexOf","base","slice","callbacks","resetForm","push","clearForm","includeHidden","oldSuccess","textStatus","jqXHR","successArguments","replaceTarget","$target","each","isArray","merge","status","xhr","context","i","max","error","oldError","complete","oldComplete","hasFileInputs","filter","mp","multipart","fileAPI","jqxhr","shouldUseFrame","iframe","closeKeepAlive","fileUploadIframe","append","name","value","serializedData","deepSerialize","s","contentType","processData","cache","uploadProgress","upload","addEventListener","event","percent","position","loaded","total","lengthComputable","Math","ceil","beforeSend","o","formData","ajax","fileUploadXhr","removeData","k","part","serialized","len","result","replace","decodeURIComponent","g","id","$io","io","sub","n","timeoutHandle","callbackProcessed","deferred","Deferred","abort","removeAttr","Date","getTime","ownerDocument","$body","abortUpload","rejection","aborted","contentWindow","execCommand","ignore","reject","active","timeout","clearTimeout","iframeTarget","remove","responseXML","setAttribute","css","responseText","statusText","getAllResponseHeaders","getResponseHeader","setRequestHeader","global","disabled","getDoc","frame","doc","err","contentDocument","csrf_token","csrf_param","posts","setFormAttribute","doSubmit","t","et","skipEncodingOverride","cb","extraInputs","addHiddenInput","input","appendTo","isPlainObject","single","fields","f","attachEvent","checkState","state","readyState","submit","removeAttribute","origin","protocol","host","isSameOrigin","forceSync","domCheckCount","detachEvent","removeEventListener","errMsg","isXml","XMLDocument","isXMLDoc","body","innerHTML","docRoot","documentElement","header","Number","getAttribute","dt","scr","textarea","ta","getElementsByTagName","pre","b","textContent","innerText","httpData","resolve","ct","xml","nodeName","dataFilter","JSON","parse","globalEval","ajaxForm","delegation","on","selector","c","isReady","off","beforeFormUnbind","ajaxFormUnbind","els2","j","v","jmax","formId","els","proto","HTMLFormElement","descriptor","getOwnPropertyDescriptor","formElements","makeArray","concat","map","fieldValue","constructor","required","$input","formSerialize","fieldSerialize","successful","tag","checked","selectedIndex","index","ops","one","op","selected","attributes","specified","text","clearFields","clearInputs","re","replaceWith","clone","is","defaultChecked","defaultValue","select","parents","multiple","defaultSelected","find","forEl","htmlFor","getElementById","add","reset","nodeType","enable","$sel","parent","jQuery"],"mappings":";;;;;;;;;;;;;;;;;;;;;sQAuBA,SAAWA,gBAwCT,IAAIC,EAAQ,SAKRC,EAAU,CAAA,EAEdA,EAAQC,aAAoDC,IAA1CJ,EAAE,uBAAuBK,IAAI,GAAGC,MAClDJ,EAAQK,cAAsC,IAApBC,OAAOC,SAEjC,IAAIC,IAAYV,EAAEW,GAAGC,KAEjBC,EAASC,OAAOC,UAAUC,eAI1BC,EAAYC,SAASC,cAAc,QAiBvC,SAASC,EAAQC,GACf,MAA6B,iBAAfA,EAAGD,QAAuBC,EAAGD,QAAQE,cAAgB,EACrE,CAo9BA,SAASC,EAAaC,GAEpB,IAAIC,EAAUD,EAAEE,KAEXF,EAAEG,uBAELH,EAAEI,iBACF5B,EAAEwB,EAAEK,QAAQC,QAAQ,QAAQC,WAAWN,GAE3C,CAEA,SAASO,EAAyBR,GAGhC,IAAIS,EAAMjC,EAAEwB,EAAEK,QAAQC,QAAQ,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,KAAK,yBAAyBI,IAAIH,GAAOvM,OAAO,yBAAyBvB,aAErE,EAET,IAAK,OAUH,OANwB,mBAAf7C,KAAK+Q,OACW,iBAAf/Q,KAAK+Q,QAAuB/Q,KAAK+Q,MAAMC,WAE/ChR,KAAK+Q,SAGA,EAET,QAGE,OAFAtT,EAAGiT,KAAK,oCAAoC7N,aAErC,EAEb,EACF,EAKAzG,EAAEW,GAAGkU,OAAS,SAAUxE,GAKtB,YAJiB,IAANA,IACTA,GAAI,GAGCzM,KAAKuD,KAAK,WACfvD,KAAKmJ,UAAYsD,CACnB,EACF,EAMArQ,EAAEW,GAAG2S,SAAW,SAAUY,GAKxB,YAJsB,IAAXA,IACTA,GAAS,GAGJtQ,KAAKuD,KAAK,WACf,IAAIuG,EAAI9J,KAAK1B,KAEb,GAAU,aAANwL,GAA0B,UAANA,EACtB9J,KAAKoP,QAAUkB,OACV,GAAsB,WAAlB9S,EAAQwC,MAAoB,CACrC,IAAIkR,EAAO9U,EAAE4D,MAAMmR,OAAO,UAEtBb,GAAUY,EAAK,IAAuB,eAAjBA,EAAK,GAAG5S,MAE/B4S,EAAKR,KAAK,UAAUhB,UAAS,GAG/B1P,KAAK0P,SAAWY,CAClB,CACF,EACF,EAGAlU,EAAEW,GAAGoB,WAAWmB,OAAQ,CAgBzB,CA5iDD,CA4iDG8R"} \ No newline at end of file +{"version":3,"file":"jquery.form.min.js","sources":["../src/form-members.js","../src/submitter.js","../src/diagnostics.js","../src/options.js","../src/ajax-form.js","../src/form-attributes.js","../src/successful-controls.js","../src/xhr-transport.js","../src/iframe-post.js","../src/iframe-response.js","../src/iframe-lifecycle.js","../src/iframe-transport.js","../src/submission.js","../src/jquery.form.js"],"sourcesContent":["// Form members: the properties and methods the plugin reads or calls on a form. A control named\n// like a member (elements, setAttribute) shadows that member on the form itself, so members are\n// read through the DOM prototypes, which a control cannot shadow.\n\n// The prototype chain of a form, nearest first. Looked up on every call: old browsers have no\n// DOM prototypes, and tests remove them.\nvar owners = [\"HTMLFormElement\", \"HTMLElement\", \"Element\", \"Node\"];\n\n// A form no control can shadow, for methods when the DOM has no prototypes to read them from.\nvar plainForm = document.createElement(\"form\");\n\nfunction findDescriptor(name) {\n for (var i = 0; i < owners.length; i++) {\n var owner = window[owners[i]];\n var descriptor = owner && Object.getOwnPropertyDescriptor(owner.prototype, name);\n\n if (descriptor) {\n return descriptor;\n }\n }\n\n return null;\n}\n\n/**\n * Reads a member of a form through its prototype getter.\n * Falls back to the plain property without DOM prototypes, or on an element the getter does not\n * accept (such as a fieldset for `elements`).\n */\nexport function formMember(form, name) {\n var descriptor = findDescriptor(name);\n\n try {\n return descriptor.get.call(form);\n } catch (e) {\n return form[name];\n }\n}\n\n/**\n * Calls a method of a form through its prototype, or through an unshadowed form without DOM\n * prototypes.\n */\nexport function callFormMethod(form, name) {\n var descriptor = findDescriptor(name);\n var method = descriptor ? descriptor.value : plainForm[name];\n\n return method.apply(form, Array.prototype.slice.call(arguments, 2));\n}\n\n// Nodes such as the document and text nodes have no tag name (#600).\nexport function tagName(el) {\n var name = formMember(el, \"tagName\");\n\n return typeof name === \"string\" ? name.toLowerCase() : \"\";\n}\n\n// Elements only: the subject of formToArray may also be the document or a plain object.\nexport function isElement(node) {\n return formMember(node, \"nodeType\") === 1;\n}\n\n// A control named parentNode makes every parentNode walk (jQuery's trigger and closest among\n// them) cycle between the form and the control.\nexport function assertRealParent(el) {\n if (el.parentNode !== formMember(el, \"parentNode\")) {\n throw new Error(\n 'jquery.form: a form control named \"parentNode\" hides the form\\'s parentNode; rename the control'\n );\n }\n}\n\n// The element itself or its nearest ancestor with one of the tag names, through the real tree.\nexport function closestByTag(el, names) {\n for (var node = el; node; node = formMember(node, \"parentNode\")) {\n if (names.indexOf(tagName(node)) >= 0) {\n return node;\n }\n }\n\n return null;\n}\n","import { closestByTag, formMember } from \"./form-members.js\";\nimport jQuery from \"jquery\";\n\n// The submitter: the button that submitted a form, captured from ajaxForm's clicks. It is kept in\n// a private store and cleared shortly after the click. The form's clk, clk_x and clk_y properties\n// are still written for pages that read them, and read when the store has none.\n\nvar storeKey = \"jqFormSubmitter\";\n\n// Writes a property on the form; a control with that name makes it read-only.\nfunction setExpando(form, name, value) {\n try {\n form[name] = value;\n } catch (ignore) {\n // the control keeps the name; the store has the submitter\n }\n}\n\n// A property the page set on the form, never a control of the form with that name.\nfunction expando(form, name) {\n var value = form[name];\n var els = formMember(form, \"elements\");\n\n return els && value && els.namedItem(name) === value ? undefined : value;\n}\n\n// Records a submitter for a form until the click window ends.\nfunction record(form, el, x, y) {\n jQuery.data(form, storeKey, { el: el, x: x, y: y });\n setExpando(form, \"clk\", el);\n\n if (el.type === \"image\") {\n setExpando(form, \"clk_x\", x);\n setExpando(form, \"clk_y\", y);\n }\n\n // clear form vars\n setTimeout(function () {\n jQuery.data(form, storeKey, null);\n setExpando(form, \"clk\", null);\n setExpando(form, \"clk_x\", null);\n setExpando(form, \"clk_y\", null);\n }, 100);\n}\n\n// The clicked point of an image button, relative to the image.\nfunction imagePoint(e, target) {\n if (typeof e.offsetX !== \"undefined\") {\n return [e.offsetX, e.offsetY];\n }\n\n if (typeof jQuery.fn.offset === \"function\") {\n var offset = jQuery(target).offset();\n\n return [e.pageX - offset.left, e.pageY - offset.top];\n }\n\n return [e.pageX - target.offsetLeft, e.pageY - target.offsetTop];\n}\n\n/**\n * Records the submit or image button a click event reached, for the form it belongs to.\n */\nexport function captureSubmitter(e) {\n // the clicked control, or the button around the clicked content (ex: a span within a button)\n var target = closestByTag(e.target, [\"button\", \"input\"]);\n\n // the type property, unlike the attribute, is \"submit\" for a button without a type (#588)\n if (!target || (target.type !== \"submit\" && target.type !== \"image\")) {\n return;\n }\n\n var form = target.form;\n\n if (!form) {\n // a submit control that belongs to no form\n return;\n }\n\n var point = target.type === \"image\" ? imagePoint(e, target) : [];\n\n record(form, target, point[0], point[1]);\n}\n\n/**\n * Records the submitter a submit event names (SubmitEvent.submitter), when no click was captured.\n * An image submitter gets the point 0,0, as native submission sends it without a click.\n */\nexport function captureEventSubmitter(e, form) {\n var el = e.originalEvent && e.originalEvent.submitter;\n\n if (el && !submitterOf(form)) {\n record(form, el, 0, 0);\n }\n}\n\n/**\n * The form's submitter as { el, x, y } (x and y for an image button), or null.\n */\nexport function submitterOf(form) {\n if (!form) {\n return null;\n }\n\n var stored = jQuery.data(form, storeKey);\n\n if (stored) {\n return stored;\n }\n\n var el = expando(form, \"clk\");\n\n return el ? { el: el, x: expando(form, \"clk_x\"), y: expando(form, \"clk_y\") } : null;\n}\n\n/**\n * The submitter's fields for a post that adds them itself (the iframe upload), as name → value.\n */\nexport function submitterFields(form) {\n var fields = {};\n var sub = submitterOf(form);\n var el = sub && sub.el;\n\n if (el && el.name && !el.disabled) {\n fields[el.name] = el.value;\n if (el.type === \"image\") {\n fields[el.name + \".x\"] = sub.x;\n fields[el.name + \".y\"] = sub.y;\n }\n }\n\n return fields;\n}\n\n/**\n * The form's submitter element, or null.\n */\nexport function submitterElement(form) {\n var sub = submitterOf(form);\n\n return sub ? sub.el : null;\n}\n","import jQuery from \"jquery\";\n\n// Debug logging, switched on by $.fn.ajaxSubmit.debug. The flag is read on every call, so it can\n// be turned on after the plugin loads.\nexport function log() {\n if (!jQuery.fn.ajaxSubmit.debug) {\n return;\n }\n\n var msg = \"[jquery.form] \" + Array.prototype.join.call(arguments, \"\");\n\n if (window.console && window.console.log) {\n window.console.log(msg);\n } else if (window.opera && window.opera.postError) {\n window.opera.postError(msg);\n }\n}\n\nvar warned = {};\n\n/**\n * A deprecation warning: console.warn, only while debug is on, once per id per page. The message\n * names the replacement; the warning adds that the feature is removed in 5.0.\n */\nexport function deprecate(id, message) {\n if (!jQuery.fn.ajaxSubmit.debug || warned[id]) {\n return;\n }\n\n warned[id] = true;\n\n if (window.console && typeof window.console.warn === \"function\") {\n window.console.warn(\"[jquery.form] \" + message + \" (removed in 5.0)\");\n }\n}\n\n// Forgets which deprecations have warned (for tests).\nexport function resetDeprecations() {\n warned = {};\n}\n\n// True for a jQuery version string older than 3.5.\nexport function beforeJQuery35(version) {\n var parts = String(version).split(\".\");\n var major = Number(parts[0]);\n\n return major < 3 || (major === 3 && Number(parts[1]) < 5);\n}\n\n// 5.0 needs jQuery 3.5 or later: warned on the first ajaxSubmit or ajaxForm, given jQuery's version.\nexport function deprecateOldJQuery(version) {\n if (beforeJQuery35(version)) {\n deprecate(\n \"jquery\",\n \"support for jQuery \" + version + \" is deprecated, 5.0 needs jQuery 3.5 or later\"\n );\n }\n}\n","// The arguments ajaxSubmit and ajaxForm accept in place of an options object.\n\n/**\n * Turns the (url, data, dataType, success) shorthand into options. A url of false is kept as\n * the url; anything else is returned as given.\n */\nexport function shorthandOptions(options, data, dataType, onSuccess) {\n if (typeof options !== \"string\" && options !== false) {\n return options;\n }\n\n var result = { url: options, data: data, dataType: dataType };\n\n if (typeof onSuccess === \"function\") {\n result.success = onSuccess;\n }\n\n return result;\n}\n\n// A copy of options without its url, so the form action is used.\nfunction withoutUrl(options) {\n var result = {};\n\n for (var key in options) {\n if (key !== \"url\" && Object.prototype.hasOwnProperty.call(options, key)) {\n result[key] = options[key];\n }\n }\n\n return result;\n}\n\n/**\n * The options ajaxSubmit starts from: a function is the success callback, the shorthand is\n * expanded, and no options at all is an empty object. A url of false or \"\" means the form action.\n */\nexport function submitOptions(options, data, dataType, onSuccess) {\n if (typeof options === \"function\") {\n return { success: options };\n }\n\n options = shorthandOptions(options, data, dataType, onSuccess);\n\n if (typeof options === \"undefined\") {\n return {};\n }\n\n return options.url === false || options.url === \"\" ? withoutUrl(options) : options;\n}\n\n/**\n * jQuery treats `context` as a flat option: after a deep merge, the settings get back the\n * caller's own object from the last source that has one, so `this` in callbacks is that object.\n */\nexport function keepContext(settings, sources) {\n for (var i = 0; i < sources.length; i++) {\n if (sources[i].context !== undefined) {\n settings.context = sources[i].context;\n }\n }\n\n return settings;\n}\n","import { assertRealParent, closestByTag, formMember, isElement } from \"./form-members.js\";\nimport { captureEventSubmitter, captureSubmitter } from \"./submitter.js\";\nimport { deprecate, deprecateOldJQuery, log } from \"./diagnostics.js\";\nimport jQuery from \"jquery\";\nimport { shorthandOptions } from \"./options.js\";\n\n// ajaxForm binding: the submit and click handlers that send a form through ajaxSubmit. The\n// handlers look up $.fn.ajaxSubmit when they run, so a replacement installed later is used.\n\n// Sends the submit event's form with ajaxSubmit, unless an earlier handler cancelled it.\nfunction submitWith(e, options) {\n if (!e.isDefaultPrevented()) {\n // if event has been canceled, don't proceed\n e.preventDefault();\n // the form is found through the real tree: a control named nodeType misleads jQuery's closest\n var form = closestByTag(e.target, [\"form\"]);\n\n // a button outside the form (form attribute), or requestSubmit(button), sends no click here\n captureEventSubmitter(e, form);\n jQuery(form).ajaxSubmit(options); // #365\n }\n}\n\nfunction doAjaxSubmit(e) {\n submitWith(e, e.data);\n}\n\nfunction captureSubmittingElement(e) {\n /* jshint validthis:true */\n assertRealParent(this);\n captureSubmitter(e);\n}\n\n// An empty selection: queued until the DOM is ready (old jQuery keeps the selector), or dropped.\nfunction bindLater($sel, options) {\n var o = { s: $sel.selector, c: $sel.context };\n\n if (!jQuery.isReady && o.s) {\n log(\"DOM not ready, queuing ajaxForm\");\n deprecate(\n \"queue\",\n \"queuing ajaxForm until the DOM is ready is deprecated, call ajaxForm inside $(fn) \" +\n 'or use delegation: \"\"'\n );\n jQuery(function () {\n jQuery(o.s, o.c).ajaxForm(options);\n });\n\n return $sel;\n }\n\n // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready()\n log(\"terminating; zero elements found by selector\" + (jQuery.isReady ? \"\" : \" (DOM not ready)\"));\n\n return $sel;\n}\n\n// delegation: true on jQuery 3 and later, where the selection has no selector: always warned,\n// debug or not, once per ajaxForm call.\nfunction warnUnscoped() {\n var console = window.console || {};\n\n if (typeof console.warn === \"function\") {\n console.warn(\n \"[jquery.form] delegation: true binds every form on the page on jQuery 3 and later; \" +\n 'pass a selector instead, e.g. delegation: \"form.ajax\"'\n );\n }\n}\n\nfunction bindDelegated($sel, options) {\n if ($sel.selector === undefined) {\n warnUnscoped();\n }\n\n jQuery(document)\n .off(\"submit.form-plugin\", $sel.selector, doAjaxSubmit)\n .off(\"click.form-plugin\", $sel.selector, captureSubmittingElement)\n .on(\"submit.form-plugin\", $sel.selector, options, doAjaxSubmit)\n .on(\"click.form-plugin\", $sel.selector, options, captureSubmittingElement);\n\n return $sel;\n}\n\n// The element itself or its nearest ancestor that matches the selector. The walk never reads a\n// parentNode a control can hide (jQuery's delegated walk does, and cycles on such a form).\nfunction closestMatch(el, selector) {\n if (!isElement(el)) {\n return null;\n }\n\n if (window.Element && Element.prototype.closest) {\n return Element.prototype.closest.call(el, selector);\n }\n\n for (var node = el; node && isElement(node); node = formMember(node, \"parentNode\")) {\n if (jQuery(node).is(selector)) {\n return node;\n }\n }\n\n return null;\n}\n\n// The document handlers bound for each delegation selector, keyed by \"s\" + selector.\nvar delegated = {};\n\nfunction unbindSelector(selector) {\n var handlers = delegated[\"s\" + selector];\n\n if (handlers) {\n jQuery(document)\n .off(\"submit.form-plugin\", handlers.submit)\n .off(\"click.form-plugin\", handlers.click);\n delete delegated[\"s\" + selector];\n }\n}\n\n// delegation: \"\": one handler pair on the document, scoped to the selector.\nfunction bindSelector($sel, selector, options) {\n if (!selector) {\n throw new Error(\"jquery.form: delegation needs a selector, or true\");\n }\n\n var handlers = {\n submit: function (e) {\n if (closestMatch(e.target, selector)) {\n submitWith(e, options);\n }\n },\n click: function (e) {\n if (closestMatch(e.target, selector)) {\n captureSubmitter(e);\n }\n },\n };\n\n unbindSelector(selector);\n delegated[\"s\" + selector] = handlers;\n jQuery(document)\n .on(\"submit.form-plugin\", handlers.submit)\n .on(\"click.form-plugin\", handlers.click);\n\n return $sel;\n}\n\n// Passed by ajaxForm's own rebind: unbind the selection only, never the document handlers.\nvar selectionOnly = {};\n\n/**\n * ajaxForm() binds the selected forms so a submit is sent with ajaxSubmit, with the clicked\n * submit button (and image coordinates) included. The options work as for ajaxSubmit.\n */\nexport function ajaxForm(options, data, dataType, onSuccess) {\n deprecateOldJQuery(jQuery.fn.jquery);\n options = shorthandOptions(options, data, dataType, onSuccess) || {};\n\n if (typeof options.delegation === \"string\") {\n return bindSelector(this, options.delegation, options);\n }\n\n options.delegation = options.delegation && typeof jQuery.fn.on === \"function\";\n\n if (!options.delegation && this.length === 0) {\n return bindLater(this, options);\n }\n\n if (options.delegation) {\n return bindDelegated(this, options);\n }\n\n if (options.beforeFormUnbind) {\n options.beforeFormUnbind(this, options);\n }\n\n return this.ajaxFormUnbind(selectionOnly)\n .on(\"submit.form-plugin\", options, doAjaxSubmit)\n .on(\"click.form-plugin\", options, captureSubmittingElement);\n}\n\n/**\n * ajaxFormUnbind() removes the handlers ajaxForm bound on the selection and every delegated\n * binding on the document. ajaxFormUnbind(selector) removes only that delegation selector.\n */\nexport function ajaxFormUnbind(selector) {\n if (typeof selector === \"string\") {\n unbindSelector(selector);\n\n return this;\n }\n\n if (selector !== selectionOnly) {\n delegated = {};\n jQuery(document).off(\"submit.form-plugin click.form-plugin\");\n }\n\n return this.off(\"submit.form-plugin click.form-plugin\");\n}\n","import { callFormMethod, isElement } from \"./form-members.js\";\nimport jQuery from \"jquery\";\n\n/**\n * An attribute of a form, or undefined when it is absent, as jQuery's attr returns it. The\n * subject may also be the document or a plain object, read through jQuery.\n */\nexport function formAttribute(form, name) {\n if (!isElement(form)) {\n return jQuery(form).attr(name);\n }\n\n var value = callFormMethod(form, \"getAttribute\", name);\n\n return value === null ? undefined : value;\n}\n","import { callFormMethod, formMember, isElement, tagName } from \"./form-members.js\";\nimport { formAttribute } from \"./form-attributes.js\";\nimport jQuery from \"jquery\";\nimport { submitterOf } from \"./submitter.js\";\n\n// Successful controls: which controls of a form are sent, and as which name/value fields\n// (https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constructing-the-form-data-set).\n\n// Line breaks, sent as CRLF\nvar rLineBreak = /\\r\\n|\\r|\\n/g;\nvar rCR = /\\r/g;\n\n// Listed form elements that are never submitted.\nvar rUnsubmittable = /^(?:fieldset|object|output)$/;\n\n/**\n * Whether a control or option is disabled, also through a disabled fieldset or optgroup. Without\n * selector matching, only its own disabled property is read.\n */\nfunction isDisabled(el) {\n return typeof el.matches === \"function\" ? el.matches(\":disabled\") : !!el.disabled;\n}\n\n/**\n * The successful-control rule: whether a control is sent. `submitter` is the button that\n * submitted the control's form; other submit and image buttons of a form are not sent.\n */\nexport function isSuccessful(el, submitter) {\n var t = el.type;\n\n if (!el.name || isDisabled(el) || t === \"reset\" || t === \"button\") {\n return false;\n }\n\n if (t === \"checkbox\" || t === \"radio\") {\n return !!el.checked;\n }\n\n if (t === \"submit\" || t === \"image\") {\n return !el.form || submitter === el;\n }\n\n return tagName(el) !== \"select\" || el.selectedIndex !== -1;\n}\n\n// The value of a select: the selected option's value for one, a list for several.\nfunction selectValue(el) {\n var index = el.selectedIndex;\n\n if (index < 0) {\n return null;\n }\n\n var a = [],\n ops = el.options;\n var one = el.type === \"select-one\";\n var max = one ? index + 1 : ops.length;\n\n for (var i = one ? index : 0; i < max; i++) {\n var op = ops[i];\n\n if (op.selected && !isDisabled(op)) {\n var v = op.value;\n\n if (!v) {\n // extra pain for IE...\n v =\n op.attributes && op.attributes.value && !op.attributes.value.specified\n ? op.text\n : op.value;\n }\n\n if (one) {\n return v;\n }\n\n a.push(v);\n }\n }\n\n return a;\n}\n\n/**\n * The value of a control, whether or not it is successful: a list for a multiple select, null\n * for a select with nothing selected, otherwise a string with CRLF line breaks (a lone CR or LF\n * included).\n */\nexport function valueOf(el) {\n if (tagName(el) === \"select\") {\n return selectValue(el);\n }\n\n var v = jQuery(el).val();\n var raw = el.value;\n\n // jQuery before 4.0 drops carriage returns from .val(); read them from the value itself\n if (typeof raw === \"string\" && raw.replace(rCR, \"\") === v) {\n v = raw;\n }\n\n return v.replace(rLineBreak, \"\\r\\n\");\n}\n\n/**\n * The fields as a urlencoded body sends them: a selected file as its name.\n */\nexport function urlencodedFields(fields) {\n return jQuery.map(fields, function (field) {\n return field.type === \"file\" && typeof field.value !== \"string\"\n ? { name: field.name, value: field.value.name }\n : field;\n });\n}\n\n/**\n * The serialization steps. `feature` holds what the entry detected at load (fileapi).\n */\nexport function createSuccessfulControls(feature) {\n var $ = jQuery;\n\n // #386; inputs that name the form in their form attribute, other than the candidates found.\n // A form only gets the ones it owns.\n function outsideControls(formId, els, owner) {\n // hat tip @thet; the id is compared, never built into a selector\n return $(\":input[form]\")\n .filter(function () {\n return (\n this.getAttribute(\"form\") === formId &&\n (!owner || this.form === owner) &&\n $.inArray(this, els) < 0\n );\n })\n .get();\n }\n\n // A descendant of a form is a candidate unless it is a control another form owns.\n function ownedBy(els, owner) {\n return $.grep(els, function (el) {\n return typeof el.form === \"undefined\" || el.form === owner;\n });\n }\n\n /**\n * The candidate controls of a form, in order: its elements, or every descendant it owns in\n * semantic mode, then the outside controls it owns that name it.\n */\n function controlsOf(form, semantic) {\n var formId = formAttribute(form, \"id\");\n var els = formMember(form, \"elements\");\n\n if (semantic || typeof els === \"undefined\") {\n // the document is not an element; it has its own getElementsByTagName\n els = isElement(form)\n ? callFormMethod(form, \"getElementsByTagName\", \"*\")\n : form.getElementsByTagName(\"*\");\n }\n\n els = $.makeArray(els);\n\n // the subject may also be a fieldset, the document or another container\n var owner = tagName(form) === \"form\" ? form : null;\n\n if (semantic && owner) {\n els = ownedBy(els, owner);\n }\n\n // FinesseRus: in non-IE browsers outside fields are already included in form.elements.\n if (formId && (semantic || /(Edge|Trident)\\//.test(navigator.userAgent))) {\n els = els.concat(outsideControls(formId, els, owner));\n }\n\n return els;\n }\n\n // The fields of a control's value, or null when the control is not sent.\n function fieldsOf(el) {\n var n = el.name;\n // read at call time, so a page that replaces $.fieldValue changes what is sent\n var v = $.fieldValue(el, true);\n\n if (v && v.constructor === Array) {\n return $.map(v, function (value) {\n return { name: n, value: value };\n });\n }\n\n if (feature.fileapi && el.type === \"file\") {\n var files = el.files;\n\n // #180: an empty field when no file is selected\n return files.length\n ? $.map(files, function (file) {\n return { name: n, value: file, type: el.type };\n })\n : [{ name: n, value: \"\", type: el.type }];\n }\n\n if (v === null || typeof v === \"undefined\") {\n return null;\n }\n\n return [{ name: n, value: v, type: el.type, required: el.required }];\n }\n\n // The clicked image's value and coordinates.\n function imageFields(sub, input, type) {\n var n = input.name;\n var value = { name: n, value: $(input).val() };\n\n if (type) {\n value.type = type;\n }\n\n return [value, { name: n + \".x\", value: sub.x }, { name: n + \".y\", value: sub.y }];\n }\n\n // Adds one candidate control's fields, and the control when it has a value to send.\n function addCandidate(collected, form, el, semantic) {\n if (!el.name || isDisabled(el) || rUnsubmittable.test(tagName(el))) {\n return;\n }\n\n var sub = semantic && el.type === \"image\" && submitterOf(form);\n\n if (sub) {\n // handle image inputs on the fly when semantic == true\n if (sub.el === el) {\n collected.fields.push.apply(collected.fields, imageFields(sub, el, el.type));\n }\n\n return;\n }\n\n var own = fieldsOf(el);\n\n if (own) {\n collected.controls.push(el);\n collected.fields.push.apply(collected.fields, own);\n }\n }\n\n // input type=='image' are not found in elements array! handle it here\n function addClickedImage(collected, form) {\n var sub = submitterOf(form);\n var input = sub && $(sub.el)[0];\n\n if (input && input.name && !isDisabled(input) && input.type === \"image\") {\n collected.fields.push.apply(collected.fields, imageFields(sub, input));\n }\n }\n\n /**\n * The fields of a form, as formToArray returns them, and the controls they came from.\n */\n function collect(form, semantic, filtering) {\n var collected = { fields: [], controls: [] };\n\n if (!form) {\n return collected;\n }\n\n var els = controlsOf(form, semantic);\n\n if (typeof filtering === \"function\") {\n els = $.map(els, filtering);\n }\n\n for (var i = 0; i < els.length; i++) {\n addCandidate(collected, form, els[i], semantic);\n }\n\n if (!semantic) {\n addClickedImage(collected, form);\n }\n\n return collected;\n }\n\n return {\n controlsOf: controlsOf,\n fieldsOf: fieldsOf,\n collect: collect,\n };\n}\n","import jQuery from \"jquery\";\nimport { keepContext } from \"./options.js\";\n\n// The XMLHttpRequest transports: $.ajax with the encoded fields, or FormData for file uploads.\nvar $ = jQuery;\n\n// utility fn for deep serialization: [name, value] pairs, as $.param encodes them\nexport function deepSerialize(extraData, traditional) {\n var param = $.param(extraData, traditional);\n var serialized = param ? param.split(\"&\") : [];\n var len = serialized.length;\n var result = [];\n var i, part;\n\n for (i = 0; i < len; i++) {\n // #252; undo param space replacement\n serialized[i] = serialized[i].replace(/\\+/g, \" \");\n part = serialized[i].split(\"=\");\n // #278; use array instead of object storage, favoring array serializations\n result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]);\n }\n\n return result;\n}\n\n/**\n * Posts the fields and extraData as FormData, for files with the File API.\n * XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz)\n */\nexport function sendFormData(submission) {\n var options = submission.options;\n var a = submission.fields;\n\n var formdata = new FormData();\n\n for (var i = 0; i < a.length; i++) {\n formdata.append(a[i].name, a[i].value);\n }\n\n if (options.extraData) {\n var serializedData = deepSerialize(options.extraData, submission.traditional);\n\n for (i = 0; i < serializedData.length; i++) {\n formdata.append(serializedData[i][0], serializedData[i][1]);\n }\n }\n\n options.data = null;\n\n var s = $.extend(true, {}, $.ajaxSettings, options, {\n contentType: false,\n processData: false,\n cache: false,\n type: submission.method || \"POST\",\n });\n\n keepContext(s, [$.ajaxSettings, options]);\n\n if (options.uploadProgress) {\n // workaround because jqXHR does not expose upload property: wraps the xhr factory, the\n // caller's or jQuery's\n var createXhr = s.xhr;\n\n s.xhr = function () {\n var xhr = createXhr.call(this);\n\n if (xhr.upload) {\n xhr.upload.addEventListener(\n \"progress\",\n function (event) {\n var percent = 0;\n // event.position is the deprecated name, read only when loaded is missing\n var position = event.loaded !== undefined ? event.loaded : event.position;\n var total = event.total;\n\n if (event.lengthComputable) {\n percent = Math.ceil((position / total) * 100);\n }\n\n options.uploadProgress(event, position, total, percent);\n },\n false\n );\n }\n\n return xhr;\n };\n }\n\n s.data = null;\n\n var beforeSend = s.beforeSend;\n\n s.beforeSend = function (xhr, o) {\n // Send FormData() provided by user\n if (options.formData) {\n o.data = options.formData;\n } else {\n o.data = formdata;\n }\n\n // a veto (false) cancels the upload, as on the other transports\n return beforeSend ? beforeSend.call(this, xhr, o) : undefined;\n };\n\n return $.ajax(s);\n}\n\n/**\n * Sends the encoded fields with $.ajax.\n */\nexport function sendAjax(submission) {\n return $.ajax(submission.options);\n}\n","import { callFormMethod } from \"./form-members.js\";\nimport { deepSerialize } from \"./xhr-transport.js\";\nimport jQuery from \"jquery\";\nimport { submitterFields } from \"./submitter.js\";\n\n// The iframe form post: the extra fields (submitter, CSRF, data), the form attributes set while\n// posting and restored after, and the native submit.\nvar $ = jQuery;\n\n// The form attributes an iframe upload changes while it posts.\nvar uploadAttributes = [\"action\", \"target\", \"method\", \"enctype\", \"encoding\"];\n\n// Called through the prototype: an extraData key or a form field may be named hasOwnProperty.\nvar hasOwn = Object.prototype.hasOwnProperty;\n\nfunction isGet(method) {\n return /^get$/i.test(method);\n}\n\n// Resolves both URLs through anchors, as jQuery does for crossDomain, so IE's anchor quirks\n// apply to both sides of the comparison.\nfunction isSameOrigin(url) {\n var origin = document.createElement(\"a\");\n var target = document.createElement(\"a\");\n\n origin.href = window.location.href;\n target.href = url;\n // IE fills in the host of a relative URL only once the resolved href is assigned back\n target.href = target.href; // eslint-disable-line no-self-assign\n\n return origin.protocol + \"//\" + origin.host === target.protocol + \"//\" + target.host;\n}\n\n/** Adds the clicked submitter (and an image's coordinates) to s.extraData. */\nexport function addSubmitterFields(s, form) {\n // add submitting element to data if we know it\n var fields = submitterFields(form);\n\n for (var n in fields) {\n s.extraData = s.extraData || {};\n s.extraData[n] = fields[n];\n }\n}\n\n/** Adds the page's CSRF token to s.extraData when the form is posted to the page's origin. */\nexport function addCsrfField(s, form, method, forms) {\n // Rails CSRF hack (thanks to Yvan Barthelemy); like jquery-ujs, only for the page's origin and\n // only when the form is posted, since a get form would put the token in the url\n var csrf_token = $(\"meta[name=csrf-token]\").attr(\"content\");\n var csrf_param = $(\"meta[name=csrf-param]\").attr(\"content\");\n var posts =\n !isGet(method) &&\n (!method || /post/i.test(method) || /post/i.test(forms.property(form, \"method\")));\n\n if (csrf_param && csrf_token && posts && isSameOrigin(s.url)) {\n s.extraData = s.extraData || {};\n s.extraData[csrf_param] = csrf_token;\n }\n}\n\nfunction setFormAttribute(form, name, value) {\n callFormMethod(form, \"setAttribute\", name, value);\n}\n\n/** The raw attributes the upload changes, null when absent, to put back exactly (#380). */\nexport function saveAttributes(form) {\n var saved = {};\n\n $.each(uploadAttributes, function (i, name) {\n saved[name] = callFormMethod(form, \"hasAttribute\", name)\n ? callFormMethod(form, \"getAttribute\", name)\n : null;\n });\n\n return saved;\n}\n\n/** Puts back the attributes saveAttributes recorded, removing those that were absent. */\nexport function restoreAttributes(form, saved) {\n $.each(uploadAttributes, function (i, name) {\n if (saved[name] === null) {\n callFormMethod(form, \"removeAttribute\", name);\n } else {\n setFormAttribute(form, name, saved[name]);\n }\n });\n}\n\n/** Points the form at the frame `target` with the upload's url, method and encoding. */\nexport function setUploadAttributes(form, target, method, s, forms) {\n var mp = \"multipart/form-data\";\n\n // update form attrs in IE friendly way\n setFormAttribute(form, \"target\", target);\n if (!method || /post/i.test(method)) {\n setFormAttribute(form, \"method\", \"POST\");\n } else if (isGet(method) && !isGet(forms.property(form, \"method\"))) {\n // a form posts natively only with GET or POST; other verbs keep the form's own method\n setFormAttribute(form, \"method\", \"GET\");\n }\n setFormAttribute(form, \"action\", s.url);\n\n // ie borks in some cases when setting encoding\n if (!s.skipEncodingOverride && (!method || /post/i.test(method))) {\n setFormAttribute(form, \"encoding\", mp);\n setFormAttribute(form, \"enctype\", mp);\n }\n}\n\n/** Appends a hidden input per extraData field to the form; each input is pushed onto `added`. */\nexport function addExtraInputs(form, ownerDocument, extraData, traditional, added) {\n // Builds the input with DOM properties: a name is never parsed as HTML.\n function addHiddenInput(name, value) {\n var input = ownerDocument.createElement(\"input\");\n\n input.type = \"hidden\";\n input.name = name;\n added.push($(input).val(value).appendTo(form)[0]);\n }\n\n if (extraData) {\n for (var n in extraData) {\n if (hasOwn.call(extraData, n)) {\n // if using the $.param format that allows for multiple values with the same name\n if (\n $.isPlainObject(extraData[n]) &&\n hasOwn.call(extraData[n], \"name\") &&\n hasOwn.call(extraData[n], \"value\")\n ) {\n addHiddenInput(extraData[n].name, extraData[n].value);\n } else {\n // arrays and objects become one field per value, as $.param sends them (#597)\n var single = {};\n\n single[n] = extraData[n];\n var fields = deepSerialize(single, traditional);\n\n for (var f = 0; f < fields.length; f++) {\n addHiddenInput(fields[f][0], fields[f][1]);\n }\n }\n }\n }\n }\n}\n\n/** Submits the form natively, even when a control named submit hides the method. */\nexport function submitForm(form) {\n try {\n form.submit();\n } catch (err) {\n // just in case form has element with name/id of 'submit'\n callFormMethod(form, \"submit\");\n }\n}\n","import jQuery from \"jquery\";\nimport { log } from \"./diagnostics.js\";\n\n// The iframe response reader: turns the frame's document into the mock xhr's text, XML, status\n// and dataType, then parses it as $.ajax would (dataFilter, JSON, script).\nvar $ = jQuery;\n\n/** The frame's document, or null when the browser denies access to it. */\nexport function getDoc(frame) {\n /* it looks like contentWindow or contentDocument do not\n * carry the protocol property in ie8, when running under ssl\n * frame.document is the only valid response document, since\n * the protocol is know but not on the other two objects. strange?\n * \"Same origin policy\" http://en.wikipedia.org/wiki/Same_origin_policy\n */\n\n var doc = null;\n\n // IE8 cascading access check\n try {\n if (frame.contentWindow) {\n doc = frame.contentWindow.document;\n }\n } catch (err) {\n // IE8 access denied under ssl & missing protocol\n log(\"cannot get iframe.contentWindow document: \" + err);\n }\n\n if (doc) {\n // successful getting content\n return doc;\n }\n\n try {\n // simply checking may throw in ie8 under ssl or mismatched protocol\n doc = frame.contentDocument ? frame.contentDocument : frame.document;\n } catch (err) {\n // last attempt\n log(\"cannot get iframe.contentDocument: \" + err);\n doc = frame.document;\n }\n\n return doc;\n}\n\n/** Parses the response text or XML for the given (lowercase) dataType. */\nexport function httpData(xhr, type, s) {\n // mostly lifted from jq1.4.4\n\n var ct = xhr.getResponseHeader(\"content-type\") || \"\",\n xml = (type === \"xml\" || !type) && ct.indexOf(\"xml\") >= 0,\n data = xml ? xhr.responseXML : xhr.responseText;\n\n if (xml && data.documentElement.nodeName === \"parsererror\") {\n if ($.error) {\n $.error(\"parsererror\");\n }\n }\n if (s && s.dataFilter) {\n data = s.dataFilter(data, type);\n }\n if (typeof data === \"string\") {\n if ((type === \"json\" || !type) && ct.indexOf(\"json\") >= 0) {\n data = JSON.parse(data);\n } else if (type === \"script\") {\n $.globalEval(data);\n }\n }\n\n return data;\n}\n\n// Copies the status and statusText attributes of an element onto the mock xhr.\nfunction readStatus(xhr, el) {\n // support for XHR 'status' & 'statusText' emulation :\n xhr.status = Number(el.getAttribute(\"status\")) || xhr.status;\n xhr.statusText = el.getAttribute(\"statusText\") || xhr.statusText;\n}\n\n// Fills the mock xhr from the document itself.\nfunction readDocument(doc, xhr, s, isXml) {\n var docRoot = doc.body ? doc.body : doc.documentElement;\n\n xhr.responseText = docRoot ? docRoot.innerHTML : null;\n xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;\n if (isXml) {\n s.dataType = \"xml\";\n }\n xhr.getResponseHeader = function (header) {\n // the dataType in lowercase, as $.ajax reads it\n var headers = { \"content-type\": s.dataType && s.dataType.toLowerCase() };\n\n return headers[header.toLowerCase()];\n };\n if (docRoot) {\n readStatus(xhr, docRoot);\n }\n}\n\n// A response embedded in a textarea, or text wrapped in pre or body, replaces responseText.\nfunction readEmbedded(doc, xhr, dt, s) {\n var scr = /(json|script|text)/.test(dt);\n\n if (!scr && !s.textarea) {\n return;\n }\n // see if user embedded response in textarea\n var ta = doc.getElementsByTagName(\"textarea\")[0];\n\n if (ta) {\n xhr.responseText = ta.value;\n readStatus(xhr, ta);\n } else if (scr) {\n // account for browsers injecting pre around json response\n var pre = doc.getElementsByTagName(\"pre\")[0];\n var b = doc.getElementsByTagName(\"body\")[0];\n\n if (pre) {\n xhr.responseText = pre.textContent ? pre.textContent : pre.innerText;\n } else if (b) {\n xhr.responseText = b.textContent ? b.textContent : b.innerText;\n }\n }\n}\n\n/**\n * Reads and parses the response document into the mock xhr. Returns {status, data, errMsg}, or\n * null when `retry()` asks to read the document again later (Opera's untraversable DOM).\n */\nexport function readResponse(doc, xhr, s, retry) {\n var status = \"success\",\n data,\n errMsg;\n\n try {\n var isXml = /^xml$/i.test(s.dataType) || doc.XMLDocument || $.isXMLDoc(doc);\n\n log(\"isXml=\" + isXml);\n\n if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) {\n // in some browsers (Opera) the iframe DOM is not always traversable when\n // the onload callback fires, so we loop a bit to accommodate\n if (retry()) {\n return null;\n }\n // let this fall through because server response could be an empty document\n }\n\n readDocument(doc, xhr, s, isXml);\n\n var dt = (s.dataType || \"\").toLowerCase();\n\n readEmbedded(doc, xhr, dt, s);\n\n try {\n data = httpData(xhr, dt, s);\n } catch (err) {\n status = \"parsererror\";\n xhr.error = errMsg = err || status;\n }\n } catch (err) {\n log(\"error caught: \", err);\n status = \"error\";\n xhr.error = errMsg = err;\n }\n\n return { status: status, data: data, errMsg: errMsg };\n}\n","import jQuery from \"jquery\";\nimport { log } from \"./diagnostics.js\";\n\n// The iframe upload's lifecycle: the mock xhr and the Deferred, the global ajax events, the\n// beforeSend veto, the timeout, abort and settling.\nvar $ = jQuery;\n\n/**\n * Creates the lifecycle of one upload with the merged settings `s`. `frame.stop()` stops the\n * frame's load and `frame.release()` removes or resets the frame after the upload.\n */\nexport function createLifecycle(s, frame) {\n var g,\n timeoutHandle,\n callbackProcessed,\n deferred = $.Deferred();\n\n var xhr = {\n // mock object\n aborted: 0,\n responseText: null,\n responseXML: null,\n status: 0,\n statusText: \"n/a\",\n getAllResponseHeaders: function () {},\n getResponseHeader: function () {},\n setRequestHeader: function () {},\n abort: function (status) {\n abort(status, [xhr, \"aborted\", status]);\n },\n };\n\n // #341\n deferred.abort = function (status) {\n xhr.abort(status);\n };\n\n function done() {\n return xhr.aborted || callbackProcessed;\n }\n\n // Completes an aborted upload once and rejects the Deferred with `rejection`.\n // `textStatus` replaces the default \"timeout\"/\"aborted\" text status.\n function abort(status, rejection, textStatus) {\n var e = textStatus || (status === \"timeout\" ? \"timeout\" : \"aborted\");\n\n if (done()) {\n return;\n }\n\n log(\"aborting upload... \" + e);\n xhr.aborted = 1;\n frame.stop();\n xhr.error = e;\n if (s.error) {\n s.error.call(s.context, xhr, e, status);\n }\n deferred.reject.apply(deferred, rejection);\n\n if (g) {\n $.event.trigger(\"ajaxError\", [xhr, s, e]);\n }\n\n complete(e);\n }\n\n // The global events that end every upload, cancelled ones included.\n function endGlobalEvents() {\n if (g) {\n $.event.trigger(\"ajaxComplete\", [xhr, s]);\n }\n\n if (g && !--$.active) {\n $.event.trigger(\"ajaxStop\");\n }\n }\n\n // The steps every finished or aborted upload ends with, in $.ajax order.\n function complete(status) {\n if (s.complete) {\n s.complete.call(s.context, xhr, status);\n }\n\n endGlobalEvents();\n clearTimeout(timeoutHandle);\n\n // clean up\n setTimeout(function () {\n frame.release();\n xhr.responseXML = null;\n }, 100);\n }\n\n // A beforeSend veto ends the upload as $.ajax cancels a request: no callbacks, the global\n // events end with ajaxError \"canceled\".\n function cancel() {\n if (done()) {\n return;\n }\n\n callbackProcessed = true;\n deferred.reject();\n if (g) {\n $.event.trigger(\"ajaxError\", [xhr, s, \"canceled\"]);\n }\n endGlobalEvents();\n }\n\n // Fires the start events and beforeSend; false when the upload must not be posted.\n function start() {\n g = s.global;\n // trigger ajax global events so that activity/block indicators work like normal\n if (g && $.active++ === 0) {\n $.event.trigger(\"ajaxStart\");\n }\n\n if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) {\n cancel();\n\n return false;\n }\n\n if (xhr.aborted) {\n // abort() in beforeSend already completed the upload\n return false;\n }\n\n if (g) {\n $.event.trigger(\"ajaxSend\", [xhr, s]);\n }\n\n // an ajaxSend handler may abort too\n return !xhr.aborted;\n }\n\n // Resolves the upload; returns {error} when the success callback threw.\n function succeed(data) {\n var failure;\n\n try {\n s.success.call(s.context, data, \"success\", xhr);\n } catch (err) {\n failure = { error: err };\n }\n\n deferred.resolve(xhr.responseText, \"success\", xhr);\n\n if (g) {\n $.event.trigger(\"ajaxSuccess\", [xhr, s, data]);\n }\n\n return failure;\n }\n\n // Settles the upload with the response reader's {status, data, errMsg}.\n function settle(result) {\n var status = result.status,\n errMsg = result.errMsg;\n\n if (xhr.aborted) {\n // abort() completed the upload while its response was processed\n log(\"upload aborted\");\n\n return;\n }\n\n // an emulated HTTP error status wins, as in $.ajax; a parse error is kept otherwise\n if (xhr.status && !((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)) {\n status = \"error\";\n }\n\n callbackProcessed = true;\n\n // ordering of these callbacks/triggers is odd, but that's how $.ajax does it\n if (status === \"success\") {\n var failure = succeed(result.data);\n\n complete(status);\n if (failure) {\n // the upload is settled; the success callback's exception still reaches the console\n throw failure.error;\n }\n\n return;\n }\n\n if (typeof errMsg === \"undefined\") {\n errMsg = xhr.statusText;\n }\n if (s.error) {\n s.error.call(s.context, xhr, status, errMsg);\n }\n deferred.reject(xhr, \"error\", errMsg);\n if (g) {\n $.event.trigger(\"ajaxError\", [xhr, s, errMsg]);\n }\n\n complete(status);\n }\n\n return {\n xhr: xhr,\n deferred: deferred,\n start: start,\n done: done,\n abort: abort,\n settle: settle,\n // Settles an upload that failed with an exception (ignored once aborted).\n fail: function (err) {\n settle({ status: \"error\", errMsg: err });\n },\n // Runs `onTimeout` after s.timeout, when set.\n startTimer: function (onTimeout) {\n if (s.timeout) {\n timeoutHandle = setTimeout(onTimeout, s.timeout);\n }\n },\n stopTimer: function () {\n clearTimeout(timeoutHandle);\n timeoutHandle = undefined;\n },\n };\n}\n","import {\n addCsrfField,\n addExtraInputs,\n addSubmitterFields,\n restoreAttributes,\n saveAttributes,\n setUploadAttributes,\n submitForm,\n} from \"./iframe-post.js\";\nimport { closestByTag, formMember } from \"./form-members.js\";\nimport { deprecate, log } from \"./diagnostics.js\";\nimport { getDoc, readResponse } from \"./iframe-response.js\";\nimport { createLifecycle } from \"./iframe-lifecycle.js\";\nimport jQuery from \"jquery\";\nimport { keepContext } from \"./options.js\";\n\n// The iframe transport: posts the form itself into a hidden frame and reads the response from it,\n// for file uploads without the File API or when the iframe option asks for it.\nvar $ = jQuery;\n\n/**\n * The iframe send step. `hasProp` is what the entry detected at load; `forms.property` reads a\n * form property as attr2 does.\n */\nexport function createIframeTransport(hasProp, forms) {\n var CLIENT_TIMEOUT_ABORT = 1;\n var SERVER_ABORT = 2;\n // tells apart the frames of uploads that start in the same millisecond\n var frameCount = 0;\n\n // ensure that every serialized input is still enabled\n function enableControls(elements) {\n for (var i = 0; i < elements.length; i++) {\n var el = $(elements[i]);\n\n if (hasProp) {\n el.prop(\"disabled\", false);\n } else {\n el.removeAttr(\"disabled\");\n }\n }\n }\n\n // Names the frame's window, when the page may: a cross-origin or sandboxed frame refuses.\n function nameWindow(frame, name) {\n try {\n if (frame.contentWindow) {\n frame.contentWindow.name = name;\n }\n } catch (ignore) {}\n }\n\n // The frame the form posts into: the iframeTarget, named `id` when it has no name, or a new\n // hidden frame named `id`. Returns the frame and the name the form targets.\n function createFrame(s, id, ownerDocument) {\n var $io, n;\n\n if (s.iframeTarget) {\n $io = $(s.iframeTarget, ownerDocument);\n n = $io.attr(\"name\");\n if (!n) {\n $io.attr(\"name\", id);\n // a frame already in the page keeps the browsing context name it was inserted with\n $io.each(function () {\n nameWindow(this, id);\n });\n } else {\n id = n;\n }\n } else {\n var io = ownerDocument.createElement(\"iframe\");\n\n io.setAttribute(\"name\", id);\n io.setAttribute(\"src\", s.iframeSrc);\n $io = $(io);\n $io.css({ position: \"absolute\", top: \"-1000px\", left: \"-1000px\" });\n }\n\n return { $io: $io, id: id };\n }\n\n // The frame hooks the lifecycle calls: stop a load in progress, and release after the upload.\n function frameHooks(s, $io) {\n return {\n stop: function () {\n try {\n // #214, #257\n if ($io[0].contentWindow.document.execCommand) {\n $io[0].contentWindow.document.execCommand(\"Stop\");\n }\n } catch (ignore) {}\n\n $io.attr(\"src\", s.iframeSrc); // abort op in progress\n },\n release: function () {\n if (!s.iframeTarget) {\n $io.remove();\n } else {\n // adding else to clean up existing iframe response.\n $io.attr(\"src\", s.iframeSrc);\n }\n },\n };\n }\n\n function listen(io, cb) {\n if (io.attachEvent) {\n io.attachEvent(\"onload\", cb);\n } else {\n io.addEventListener(\"load\", cb, false);\n }\n }\n\n function unlisten(io, cb) {\n if (io.detachEvent) {\n io.detachEvent(\"onload\", cb);\n } else {\n io.removeEventListener(\"load\", cb, false);\n }\n }\n\n // private function for handling file uploads (hat tip to YAHOO!)\n function fileUploadIframe(submission) {\n var form = submission.form,\n method = submission.method;\n\n var s = keepContext($.extend(true, {}, $.ajaxSettings, submission.options), [\n $.ajaxSettings,\n submission.options,\n ]);\n\n s.context = s.context || s;\n var ownerDocument = formMember(form, \"ownerDocument\");\n var $body = $(closestByTag(form, [\"body\"]));\n var frame = createFrame(s, \"jqFormIO\" + new Date().getTime() + frameCount++, ownerDocument);\n var $io = frame.$io,\n io = $io[0];\n var life = createLifecycle(s, frameHooks(s, $io));\n var domCheckCount = 50;\n\n if (!life.start()) {\n return life.deferred;\n }\n\n addSubmitterFields(s, form);\n addCsrfField(s, form, method, forms);\n\n // look for server aborts\n function checkState() {\n try {\n var state = getDoc(io).readyState;\n\n log(\"state = \" + state);\n if (state && state.toLowerCase() === \"uninitialized\") {\n setTimeout(checkState, 50);\n }\n } catch (e) {\n log(\"Server abort: \", e, \" (\", e.name, \")\");\n cb(SERVER_ABORT);\n life.stopTimer();\n }\n }\n\n // take a breath so that pending repaints get some cpu time before the upload starts\n function doSubmit() {\n var saved = saveAttributes(form);\n\n setUploadAttributes(form, frame.id, method, s, forms);\n\n // support timout\n life.startTimer(function () {\n cb(CLIENT_TIMEOUT_ABORT);\n });\n\n // add \"extra\" data to form if provided in options\n var extraInputs = [];\n\n try {\n addExtraInputs(form, ownerDocument, s.extraData, submission.traditional, extraInputs);\n\n if (!s.iframeTarget) {\n // add iframe to doc and submit the form\n $io.appendTo($body);\n }\n\n // A connected form posting into a frame outside the document opens a new window.\n var root = ownerDocument.documentElement;\n\n if (io && $.contains(root, form) && !$.contains(root, io)) {\n var notInDocument = \"jquery.form: the upload frame is not in the document\";\n\n life.abort(notInDocument, [life.xhr, \"error\", notInDocument], \"error\");\n\n return;\n }\n\n listen(io, cb);\n setTimeout(checkState, 15);\n submitForm(form);\n } finally {\n // reset attrs and remove \"extra\" input elements\n restoreAttributes(form, saved);\n $(extraInputs).remove();\n }\n }\n\n // Reads the next document by Opera's rules: false once the retries are used up.\n function retry() {\n if (--domCheckCount) {\n log(\"requeing onLoad callback, DOM not available\");\n setTimeout(cb, 250);\n\n return true;\n }\n\n return false;\n }\n\n function cb(e) {\n if (life.done()) {\n return;\n }\n\n var doc = getDoc(io);\n\n if (!doc) {\n log(\"cannot access response document\");\n e = SERVER_ABORT;\n }\n if (e === CLIENT_TIMEOUT_ABORT) {\n life.abort(\"timeout\", [life.xhr, \"timeout\"]);\n\n return;\n }\n if (e === SERVER_ABORT) {\n life.abort(\"server abort\", [life.xhr, \"error\", \"server abort\"]);\n\n return;\n }\n\n if (doc.location.href === s.iframeSrc) {\n // response not received yet\n return;\n }\n\n unlisten(io, cb);\n\n var result = readResponse(doc, life.xhr, s, retry);\n\n if (result) {\n life.settle(result);\n }\n }\n\n // An exception while posting settles the upload with \"error\" and the exception.\n function post() {\n if (life.done()) {\n // aborted before the delayed post\n return;\n }\n\n try {\n doSubmit();\n } catch (err) {\n log(\"upload failed: \", err);\n life.fail(err);\n }\n }\n\n if (s.forceSync) {\n post();\n } else {\n setTimeout(post, 10); // this lets dom updates render\n }\n\n return life.deferred;\n }\n\n return function sendIframe(submission) {\n var jqxhr;\n\n // now, while the controls are still listed: ajaxSubmit clears the list when it returns,\n // before a closeKeepAlive request completes\n enableControls(submission.controls);\n\n // hack to fix Safari hang (thanks to Tim Molendijk for this)\n // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d\n if (submission.options.closeKeepAlive) {\n deprecate(\"closeKeepAlive\", \"closeKeepAlive works around a Safari 3/4 bug and is deprecated\");\n $.get(submission.options.closeKeepAlive, function () {\n jqxhr = fileUploadIframe(submission);\n });\n } else {\n jqxhr = fileUploadIframe(submission);\n }\n\n return jqxhr;\n };\n}\n","import { deprecate, log } from \"./diagnostics.js\";\nimport { assertRealParent } from \"./form-members.js\";\nimport jQuery from \"jquery\";\nimport { keepContext } from \"./options.js\";\nimport { urlencodedFields } from \"./successful-controls.js\";\n\n// A Submission is one ajaxSubmit call once its vetoes have passed:\n// { form, $form, fields, controls, options, method, traditional }. `options` is the object the\n// callbacks and events receive; later steps change it in place.\n\n/**\n * The submission steps. `feature` holds what the entry detected at load (fileapi, formdata), and\n * `forms` reads form attributes and attr2-style properties (attribute, property), and\n * `serialization` collects the form's fields and controls.\n */\nexport function createSubmission(feature, forms, serialization) {\n var $ = jQuery;\n\n function refuse(message) {\n log(message);\n\n return null;\n }\n\n // The options merged over the form's action, the method, and the ajax defaults.\n function withDefaults(form, options, method) {\n var action = options.url || forms.property(form, \"action\");\n var url = typeof action === \"string\" ? action.trim() : \"\";\n\n // clean url (don't include hash value); an action that is only a fragment means this page\n url = url.split(\"#\")[0] || window.location.href.split(\"#\")[0];\n // IE requires javascript:false in https, but this breaks chrome >83 and goes against spec.\n // Instead of using javascript:false always, let's only apply it for IE.\n var isMsie = /(MSIE|Trident)/.test(navigator.userAgent || \"\");\n var iframeSrc = isMsie && /^https/i.test(document.URL) ? \"javascript:false\" : \"about:blank\"; // eslint-disable-line no-script-url\n\n var merged = $.extend(\n true,\n {\n url: url,\n success: $.ajaxSettings.success,\n type: method || $.ajaxSettings.type,\n iframeSrc: iframeSrc,\n },\n options\n );\n\n return keepContext(merged, [options]);\n }\n\n /**\n * The one method every transport sends, read after the hooks: `method` wins over `type`, and\n * `type` is set to it. Undefined when only the ajax default applies, so each transport keeps\n * its own default.\n */\n function resolveMethod(options, defaultType) {\n var resolved = options.method || options.type;\n\n options.type = resolved;\n\n return resolved === defaultType && !options.method ? undefined : resolved;\n }\n\n // The data option, kept as extraData and encoded, or undefined without one.\n function extraQuery(fields, options, traditional) {\n if (!options.data) {\n return undefined;\n }\n\n var optionsData = typeof options.data === \"function\" ? options.data(fields) : options.data;\n\n if (typeof optionsData === \"string\") {\n if (options.requestFormat === \"json\") {\n throw new Error(\n 'jquery.form: requestFormat \"json\" needs object data; a string data option is a query string'\n );\n }\n\n // a query string: sent as-is when urlencoded, as its own fields otherwise\n options.extraData = queryPairs(optionsData);\n\n return optionsData;\n }\n\n options.extraData = optionsData;\n\n return $.param(optionsData, traditional);\n }\n\n // Sets a key as an own data property, so a name like __proto__ is an ordinary key.\n function defineKey(object, key, value) {\n Object.defineProperty(object, key, {\n value: value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n\n /**\n * requestFormat \"json\" (#545): the fields as an object (a repeated name gives an array), merged\n * with object data, sent as a JSON body. Based on the idea in PR #557 by zhangciwu.\n */\n function jsonBody(options, fields) {\n if (/^get$/i.test(options.type)) {\n throw new Error('jquery.form: requestFormat \"json\" needs a method with a body, such as POST');\n }\n\n var body = {};\n var own = Object.prototype.hasOwnProperty;\n\n for (var i = 0; i < fields.length; i++) {\n var name = fields[i].name;\n\n if (!own.call(body, name)) {\n defineKey(body, name, fields[i].value);\n } else if (Array.isArray(body[name])) {\n body[name].push(fields[i].value);\n } else {\n defineKey(body, name, [body[name], fields[i].value]);\n }\n }\n\n var extra = options.extraData;\n\n for (var key in extra) {\n if (own.call(extra, key)) {\n defineKey(body, key, extra[key]);\n }\n }\n\n options.data = JSON.stringify(body);\n options.contentType = \"application/json; charset=UTF-8\";\n }\n\n // The fields of a query string, as the { name, value } list $.param takes.\n function queryPairs(query) {\n var pairs = [];\n var parts = query.split(\"&\");\n\n for (var i = 0; i < parts.length; i++) {\n if (parts[i]) {\n var at = parts[i].indexOf(\"=\");\n var name = at < 0 ? parts[i] : parts[i].slice(0, at);\n var value = at < 0 ? \"\" : parts[i].slice(at + 1);\n\n pairs.push({ name: decodeQuery(name), value: decodeQuery(value) });\n }\n }\n\n return pairs;\n }\n\n function decodeQuery(text) {\n return decodeURIComponent(text.replace(/\\+/g, \" \"));\n }\n\n // Puts the encoded fields in the url for a get, and in the data otherwise.\n function encode(options, q, qx) {\n if (qx) {\n q = q ? q + \"&\" + qx : qx;\n }\n\n if (options.type.toUpperCase() === \"GET\") {\n // the query goes before any fragment in the url option\n var hashAt = options.url.indexOf(\"#\");\n var base = hashAt < 0 ? options.url : options.url.slice(0, hashAt);\n\n options.url =\n base + (base.indexOf(\"?\") >= 0 ? \"&\" : \"?\") + q + options.url.slice(base.length);\n options.data = null; // data is null for 'get'\n } else {\n options.data = q; // data is the query string for 'post'\n }\n }\n\n // A callback option as a list: an array as given, one function, or none.\n function callbackList(callback) {\n if (Array.isArray(callback)) {\n return callback;\n }\n\n return callback ? [callback] : [];\n }\n\n // Calls each callback in order with the same this and arguments.\n function callEach(callbacks, context, args) {\n for (var i = 0; i < callbacks.length; i++) {\n callbacks[i].apply(context, args);\n }\n }\n\n /**\n * Resolves the options, serializes the form, and runs the vetoes: the Submission, or null when\n * an event or callback stopped it.\n */\n function prepare($set, options) {\n $set.each(function () {\n assertRealParent(this);\n });\n\n var form = $set[0];\n var method = options.method || options.type || forms.property(form, \"method\");\n\n options = withDefaults(form, options, method);\n\n // the ajax default type, when neither the caller nor the form gave a method\n var defaultType = method ? undefined : options.type;\n\n // hook for manipulating the form data before it is extracted;\n // convenient for use with rich editors like tinyMCE or FCKEditor\n var veto = {};\n\n $set.trigger(\"form-pre-serialize\", [$set, options, veto]);\n if (veto.veto) {\n return refuse(\"ajaxSubmit: submit vetoed via form-pre-serialize trigger\");\n }\n\n // provide opportunity to alter form data before it is serialized\n if (options.beforeSerialize && options.beforeSerialize($set, options) === false) {\n return refuse(\"ajaxSubmit: submit aborted via beforeSerialize callback\");\n }\n\n var traditional = options.traditional;\n\n if (typeof traditional === \"undefined\") {\n traditional = $.ajaxSettings.traditional;\n }\n\n var collected = serialization.collect($set[0], options.semantic, options.filtering);\n var fields = collected.fields;\n var controls = collected.controls;\n var qx = extraQuery(fields, options, traditional);\n\n // give pre-submit callback an opportunity to abort the submit\n if (options.beforeSubmit && options.beforeSubmit(fields, $set, options) === false) {\n return refuse(\"ajaxSubmit: submit aborted via beforeSubmit callback\");\n }\n\n // fire vetoable 'validate' event\n $set.trigger(\"form-submit-validate\", [fields, $set, options, veto]);\n if (veto.veto) {\n return refuse(\"ajaxSubmit: submit vetoed via form-submit-validate trigger\");\n }\n\n method = resolveMethod(options, defaultType);\n\n if (options.requestFormat === \"json\") {\n jsonBody(options, fields);\n } else {\n encode(options, $.param(urlencodedFields(fields), traditional), qx);\n }\n\n return {\n form: form,\n $form: $set,\n fields: fields,\n controls: controls,\n options: options,\n method: method,\n traditional: traditional,\n };\n }\n\n /**\n * Wraps success, error and complete (a function or an array of them, as $.ajax takes) so each\n * also receives the form, and adds the resetForm,\n * clearForm and target steps before the success callbacks.\n */\n function deliver(submission) {\n var $set = submission.$form;\n var options = submission.options;\n var callbacks = [];\n\n if (options.resetForm) {\n callbacks.push(function () {\n $set.resetForm();\n });\n }\n\n if (options.clearForm) {\n callbacks.push(function () {\n $set.clearForm(options.includeHidden);\n });\n }\n\n // perform a load on the target only if dataType is not provided\n if (!options.dataType && options.target) {\n var successes = callbackList(options.success);\n\n callbacks.push(function (data, textStatus, jqXHR) {\n var successArguments = arguments,\n fn = options.replaceTarget ? \"replaceWith\" : \"html\",\n $target = $(options.target);\n\n // Only a string response is inserted. jQuery has already parsed a JSON or XML response,\n // and inserting it would parse each of its strings as HTML.\n if (typeof data === \"string\") {\n $target[fn](data);\n } else {\n log(\"target: the response was parsed by jQuery, so it is not inserted\");\n }\n\n if (!$target.length) {\n // nothing to fill: success still runs once, with the normal context\n callEach(successes, this, successArguments);\n }\n\n $target.each(function () {\n callEach(successes, this, successArguments);\n });\n });\n } else {\n $.merge(callbacks, callbackList(options.success));\n }\n\n options.success = function (data, status, xhr) {\n // jQuery 1.4+ passes xhr as 3rd arg\n var context = options.context || this; // jQuery 1.4+ supports scope context\n\n for (var i = 0, max = callbacks.length; i < max; i++) {\n callbacks[i].apply(context, [data, status, xhr || $set, $set]);\n }\n };\n\n if (options.error) {\n var errors = callbackList(options.error);\n\n options.error = function (xhr, status, error) {\n callEach(errors, options.context || this, [xhr, status, error, $set]);\n };\n }\n\n if (options.complete) {\n var completes = callbackList(options.complete);\n\n options.complete = function (xhr, status) {\n callEach(completes, options.context || this, [xhr, status, $set]);\n };\n }\n }\n\n /**\n * The transport for a submission: \"iframe\" for files without the File API or when forced,\n * \"formdata\" for files with it, \"ajax\" otherwise.\n */\n function chooseTransport(submission) {\n var $set = submission.$form;\n var options = submission.options;\n\n // [value] (issue #113), also see comment:\n // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219\n // and the file inputs outside the form that belong to it through their form attribute\n var fileInputs = $(\"input[type=file]:enabled\", $set)\n .add($(submission.controls).filter(\"input[type=file]\"))\n .filter(function () {\n return $(this).val() !== \"\";\n });\n var hasFileInputs = fileInputs.length > 0;\n // compared as the browser does: ASCII case-insensitive, without surrounding whitespace\n var mp = /^[\\t\\n\\f\\r ]*multipart\\/form-data[\\t\\n\\f\\r ]*$/i;\n var multipart =\n mp.test(forms.attribute($set[0], \"enctype\")) || mp.test(forms.attribute($set[0], \"encoding\"));\n var fileAPI = feature.fileapi && feature.formdata;\n\n log(\"fileAPI :\" + fileAPI);\n\n var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI;\n\n var transport = (hasFileInputs || multipart) && fileAPI ? \"formdata\" : \"ajax\";\n\n // options.iframe allows user to force iframe mode\n // 06-NOV-09: now defaulting to iframe mode if file input is detected\n if (options.iframe !== false && (options.iframe || shouldUseFrame)) {\n transport = \"iframe\";\n }\n\n if (transport === \"iframe\" && !options.iframe) {\n deprecate(\n \"iframe\",\n \"choosing the iframe transport automatically without FormData is deprecated, set iframe: true\"\n );\n }\n\n if (transport !== \"ajax\" && options.requestFormat === \"json\") {\n throw new Error(\n 'jquery.form: requestFormat \"json\" cannot send files or use the iframe transport'\n );\n }\n\n return transport;\n }\n\n return { prepare: prepare, deliver: deliver, chooseTransport: chooseTransport };\n}\n","/*!\n * jQuery Form Plugin\n * version: 4.5.0\n * Requires jQuery v1.7.2 or later\n * Project repository: https://github.com/jquery-form/form\n\n * Copyright 2017 Kevin Morris\n * Copyright 2006 M. Alsup\n\n * Dual licensed under the LGPL-2.1+ or MIT licenses\n * https://github.com/jquery-form/form#license\n\n * This library is free software; you can redistribute it and/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n */\nimport { ajaxForm, ajaxFormUnbind } from \"./ajax-form.js\";\nimport { callFormMethod, tagName } from \"./form-members.js\";\nimport {\n createSuccessfulControls,\n isSuccessful,\n urlencodedFields,\n valueOf,\n} from \"./successful-controls.js\";\nimport { deprecate, deprecateOldJQuery, log } from \"./diagnostics.js\";\nimport { sendAjax, sendFormData } from \"./xhr-transport.js\";\nimport { createIframeTransport } from \"./iframe-transport.js\";\nimport { createSubmission } from \"./submission.js\";\nimport { formAttribute } from \"./form-attributes.js\";\nimport jQuery from \"jquery\";\nimport { submitOptions } from \"./options.js\";\nimport { submitterElement } from \"./submitter.js\";\n\n(function ($) {\n \"use strict\";\n\n /*\n\t\tUsage Note:\n\t\t-----------\n\t\tDo not use both ajaxSubmit and ajaxForm on the same form. These\n\t\tfunctions are mutually exclusive. Use ajaxSubmit if you want\n\t\tto bind your own submit handler to the form. For example,\n\n\t\t$(document).ready(function() {\n\t\t\t$('#myForm').on('submit', function(e) {\n\t\t\t\te.preventDefault(); // <-- important\n\t\t\t\t$(this).ajaxSubmit({\n\t\t\t\t\ttarget: '#output'\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\n\t\tUse ajaxForm when you want the plugin to manage all the event binding\n\t\tfor you. For example,\n\n\t\t$(document).ready(function() {\n\t\t\t$('#myForm').ajaxForm({\n\t\t\t\ttarget: '#output'\n\t\t\t});\n\t\t});\n\n\t\tYou can also use ajaxForm with delegation (requires jQuery v1.7+), so the\n\t\tform does not have to exist when you invoke ajaxForm:\n\n\t\t$('#myForm').ajaxForm({\n\t\t\tdelegation: true,\n\t\t\ttarget: '#output'\n\t\t});\n\n\t\tWhen using ajaxForm, the ajaxSubmit function will be invoked for you\n\t\tat the appropriate time.\n\t*/\n\n /**\n * Feature detection\n */\n var feature = {};\n\n feature.fileapi = $('').get(0).files !== undefined;\n feature.formdata = typeof window.FormData !== \"undefined\";\n\n var hasProp = !!$.fn.prop;\n // What attr2 returns for a form: the property when it is a string, otherwise the attribute. The\n // property is read plainly on purpose: a control named like it shadows it, and then the raw\n // attribute is used.\n function formProperty(form, name) {\n var value = hasProp ? form[name] : undefined;\n\n return typeof value === \"string\" ? value : formAttribute(form, name);\n }\n\n var forms = { attribute: formAttribute, property: formProperty };\n var serialization = createSuccessfulControls(feature);\n var steps = createSubmission(feature, forms, serialization);\n var transports = {\n iframe: createIframeTransport(hasProp, forms),\n formdata: sendFormData,\n ajax: sendAjax,\n };\n\n // attr2 uses prop when it can but checks the return type for\n // an expected string. This accounts for the case where a form\n // contains inputs with names like \"action\" or \"method\"; in those\n // cases \"prop\" returns the element\n $.fn.attr2 = function () {\n deprecate(\"attr2\", \"attr2 is deprecated, use .prop() or .attr()\");\n\n if (!hasProp) {\n return this.attr.apply(this, arguments);\n }\n\n var val = this.prop.apply(this, arguments);\n\n if ((val && val.jquery) || typeof val === \"string\") {\n return val;\n }\n\n return this.attr.apply(this, arguments);\n };\n\n /**\n * ajaxSubmit() provides a mechanism for immediately submitting\n * an HTML form using AJAX.\n *\n * @param\t{object|string}\toptions\t\tjquery.form.js parameters or custom url for submission\n * @param\t{object}\t\tdata\t\textraData\n * @param\t{string}\t\tdataType\tajax dataType\n * @param\t{function}\t\tonSuccess\tajax success callback function\n */\n $.fn.ajaxSubmit = function (options, data, dataType, onSuccess) {\n deprecateOldJQuery($.fn.jquery);\n\n // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)\n if (!this.length) {\n log(\"ajaxSubmit: skipping submit process - no element selected\");\n\n return this;\n }\n\n // #541: jQuery's slim build has no $.ajax\n if (!$.ajax) {\n throw new Error(\n \"jquery.form: ajaxSubmit needs the full jQuery build; this jQuery has no $.ajax\"\n );\n }\n\n var submission = steps.prepare(this, submitOptions(options, data, dataType, onSuccess));\n\n if (!submission) {\n return this;\n }\n\n steps.deliver(submission);\n\n var jqxhr = transports[steps.chooseTransport(submission)](submission);\n\n this.removeData(\"jqxhr\").data(\"jqxhr\", jqxhr);\n\n // clear element array\n for (var k = 0; k < submission.controls.length; k++) {\n submission.controls[k] = null;\n }\n\n // fire 'notify' event\n this.trigger(\"form-submit-notify\", [this, submission.options]);\n\n return this;\n };\n\n $.fn.ajaxForm = ajaxForm;\n $.fn.ajaxFormUnbind = ajaxFormUnbind;\n\n /**\n * formToArray() gathers form element data into an array of objects that can\n * be passed to any of the following ajax functions: $.get, $.post, or load.\n * Each object in the array has both a 'name' and 'value' property. An example of\n * an array for a simple login form might be:\n *\n * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]\n *\n * It is this array that is passed to pre-submit callback functions provided to the\n * ajaxSubmit() and ajaxForm() methods.\n */\n $.fn.formToArray = function (semantic, elements, filtering) {\n var collected = serialization.collect(this[0], semantic, filtering);\n\n if (elements) {\n elements.push.apply(elements, collected.controls);\n }\n\n return collected.fields;\n };\n\n /**\n * Serializes form data into a 'submittable' string. This method will return a string\n * in the format: name1=value1&name2=value2\n */\n $.fn.formSerialize = function (semantic) {\n // hand off to jQuery.param for proper encoding\n return $.param(urlencodedFields(this.formToArray(semantic)));\n };\n\n /**\n * Serializes all field elements in the jQuery object into a query string.\n * This method will return a string in the format: name1=value1&name2=value2\n */\n $.fn.fieldSerialize = function (successful) {\n var a = [];\n\n this.each(function () {\n var n = this.name;\n\n // a form is not a field, though it may have a name\n if (!n || tagName(this) === \"form\") {\n return;\n }\n\n var v = $.fieldValue(this, successful);\n\n if (v && v.constructor === Array) {\n for (var i = 0, max = v.length; i < max; i++) {\n a.push({ name: n, value: v[i] });\n }\n } else if (v !== null && typeof v !== \"undefined\") {\n a.push({ name: this.name, value: v });\n }\n });\n\n // hand off to jQuery.param for proper encoding\n return $.param(a);\n };\n\n /**\n * Returns the value(s) of the element in the matched set. For example, consider the following form:\n *\n *\t
\n *\t\t\n *\t\t\n *\t\t\n *\t\t\n *\t\t\n *\t\t\n *\t
\n *\n *\tvar v = $('input[type=text]').fieldValue();\n *\t// if no values are entered into the text inputs\n *\tv === ['','']\n *\t// if values entered into the text inputs are 'foo' and 'bar'\n *\tv === ['foo','bar']\n *\n *\tvar v = $('input[type=checkbox]').fieldValue();\n *\t// if neither checkbox is checked\n *\tv === undefined\n *\t// if both checkboxes are checked\n *\tv === ['B1', 'B2']\n *\n *\tvar v = $('input[type=radio]').fieldValue();\n *\t// if neither radio is checked\n *\tv === undefined\n *\t// if first radio is checked\n *\tv === ['C1']\n *\n * The successful argument controls whether or not the field element must be 'successful'\n * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).\n * The default value of the successful argument is true. If this value is false the value(s)\n * for each element is returned.\n *\n * Note: This method *always* returns an array. If no valid value can be determined the\n *\tarray will be empty, otherwise it will contain one or more values.\n */\n $.fn.fieldValue = function (successful) {\n for (var val = [], i = 0, max = this.length; i < max; i++) {\n var el = this[i];\n var v = $.fieldValue(el, successful);\n\n if (v === null || typeof v === \"undefined\" || (v.constructor === Array && !v.length)) {\n continue;\n }\n\n if (v.constructor === Array) {\n $.merge(val, v);\n } else {\n val.push(v);\n }\n }\n\n return val;\n };\n\n /**\n * Returns the value of the field element.\n */\n $.fieldValue = function (el, successful) {\n var required = typeof successful === \"undefined\" || successful;\n\n if (required && !isSuccessful(el, submitterElement(el.form))) {\n return null;\n }\n\n return valueOf(el);\n };\n\n /**\n * Clears the form data. Takes the following actions on the form's input fields:\n * - input text fields will have their 'value' property set to the empty string\n * - select elements will have their 'selectedIndex' property set to -1\n * - checkbox and radio inputs will have their 'checked' property set to false\n * - inputs of type submit, button, reset, and hidden will *not* be effected\n * - button elements will *not* be effected\n */\n $.fn.clearForm = function (includeHidden) {\n return this.each(function () {\n $(\"input,select,textarea\", this).clearFields(includeHidden);\n });\n };\n\n /**\n * Clears the selected form elements.\n */\n $.fn.clearInputs = function (includeHidden) {\n deprecate(\"clearInputs\", \"clearInputs is deprecated, use clearFields\");\n\n return this.clearFields(includeHidden);\n };\n\n $.fn.clearFields = function (includeHidden) {\n var re =\n /^(?:color|date|datetime|datetime-local|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list\n\n return this.each(function () {\n var t = this.type,\n tag = tagName(this);\n\n if (re.test(t) || tag === \"textarea\") {\n this.value = \"\";\n } else if (t === \"checkbox\" || t === \"radio\") {\n this.checked = false;\n } else if (tag === \"select\") {\n this.selectedIndex = -1;\n } else if (t === \"file\") {\n if (/MSIE/.test(navigator.userAgent)) {\n $(this).replaceWith($(this).clone(true));\n } else {\n $(this).val(\"\");\n }\n } else if (includeHidden) {\n // includeHidden can be the value true, or it can be a selector string\n // indicating a special test; for example:\n // $('#myForm').clearForm('.special:hidden')\n // the above would clean hidden inputs that have the class of 'special'\n if (\n (includeHidden === true && /hidden/.test(t)) ||\n (typeof includeHidden === \"string\" && $(this).is(includeHidden))\n ) {\n this.value = \"\";\n }\n }\n });\n };\n\n /**\n * Resets the form data or individual elements. Takes the following actions\n * on the selected tags:\n * - all fields within form elements will be reset to their original value\n * - input / textarea / select fields will be reset to their original value\n * - option / optgroup fields (for multi-selects) will defaulted individually\n * - non-multiple options will find the right select to default\n * - label elements will be searched against its 'for' attribute\n * - all others will be searched for appropriate children to default\n */\n $.fn.resetForm = function () {\n return this.each(function () {\n var el = $(this);\n var tag = tagName(this);\n\n switch (tag) {\n case \"input\":\n this.checked = this.defaultChecked;\n\n // as the native reset: types whose value is the value attribute keep it\n if (this.type === \"file\") {\n // a file input cannot take its value attribute; the native reset empties it\n this.value = \"\";\n } else if (!/^(?:checkbox|radio|hidden|submit|reset|button|image)$/.test(this.type)) {\n this.value = this.defaultValue;\n }\n\n return true;\n\n case \"textarea\":\n this.value = this.defaultValue;\n\n return true;\n\n case \"option\":\n case \"optgroup\":\n var select = el.parents(\"select\");\n\n if (select.length && select[0].multiple) {\n if (tag === \"option\") {\n this.selected = this.defaultSelected;\n } else {\n el.find(\"option\").resetForm();\n }\n } else {\n select.resetForm();\n }\n\n return true;\n\n case \"select\":\n // in order, as the native reset: of several default options, a single select keeps the last\n el.find(\"option\").each(function () {\n this.selected = this.defaultSelected;\n });\n\n return true;\n\n case \"label\":\n // The control whose id the for attribute names, and the controls inside the label. The\n // filter keeps a for that names an ancestor from resetting the label again.\n var forEl = this.htmlFor && this.ownerDocument.getElementById(this.htmlFor);\n\n el.find(\"input,select,textarea\").add(forEl).filter(\"input,select,textarea\").resetForm();\n\n return true;\n\n case \"form\":\n // through the prototype: a control named reset shadows the method\n callFormMethod(this, \"reset\");\n\n return true;\n\n default:\n el.find(\"form,input,label,select,textarea\").resetForm();\n\n return true;\n }\n });\n };\n\n /**\n * Enables or disables any matching elements.\n */\n $.fn.enable = function (b) {\n if (typeof b === \"undefined\") {\n b = true;\n }\n\n return this.each(function () {\n this.disabled = !b;\n });\n };\n\n /**\n * Checks/unchecks any matching checkboxes or radio buttons and\n * selects/deselects and matching option elements.\n */\n $.fn.selected = function (select) {\n if (typeof select === \"undefined\") {\n select = true;\n }\n\n return this.each(function () {\n var t = this.type;\n\n if (t === \"checkbox\" || t === \"radio\") {\n this.checked = select;\n } else if (tagName(this) === \"option\") {\n var $sel = $(this).parent(\"select\");\n\n if (select && $sel[0] && $sel[0].type === \"select-one\") {\n // deselect all other options\n $sel.find(\"option\").selected(false);\n }\n\n this.selected = select;\n }\n });\n };\n\n // expose debug var\n $.fn.ajaxSubmit.debug = false;\n})(jQuery);\n\nexport default jQuery;\n"],"names":["owners","plainForm","document","createElement","findDescriptor","name","i","length","owner","window","descriptor","Object","getOwnPropertyDescriptor","prototype","formMember","form","get","call","e","callFormMethod","value","apply","Array","slice","arguments","tagName","el","toLowerCase","isElement","node","assertRealParent","parentNode","Error","closestByTag","names","indexOf","storeKey","setExpando","ignore","expando","els","namedItem","undefined","record","x","y","jQuery","data","type","setTimeout","captureSubmitter","target","point","offsetX","offsetY","fn","offset","pageX","left","pageY","top","offsetLeft","offsetTop","imagePoint","submitterOf","stored","log","ajaxSubmit","debug","msg","join","console","opera","postError","warned","deprecate","id","message","warn","deprecateOldJQuery","version","parts","String","split","major","Number","beforeJQuery35","shorthandOptions","options","dataType","onSuccess","result","url","success","submitOptions","key","hasOwnProperty","withoutUrl","keepContext","settings","sources","context","submitWith","isDefaultPrevented","preventDefault","originalEvent","submitter","captureEventSubmitter","doAjaxSubmit","captureSubmittingElement","this","bindDelegated","$sel","selector","off","on","closestMatch","Element","closest","is","delegated","unbindSelector","handlers","submit","click","selectionOnly","ajaxForm","jquery","delegation","bindSelector","beforeFormUnbind","ajaxFormUnbind","o","s","c","isReady","bindLater","formAttribute","attr","rLineBreak","rCR","rUnsubmittable","isDisabled","matches","disabled","valueOf","index","selectedIndex","a","ops","one","max","op","selected","v","attributes","specified","text","push","selectValue","val","raw","replace","urlencodedFields","fields","map","field","createSuccessfulControls","feature","$","controlsOf","semantic","formId","getElementsByTagName","makeArray","grep","ownedBy","test","navigator","userAgent","concat","filter","getAttribute","inArray","outsideControls","fieldsOf","n","fieldValue","constructor","fileapi","files","file","required","imageFields","sub","input","addCandidate","collected","own","controls","collect","filtering","addClickedImage","deepSerialize","extraData","traditional","part","param","serialized","len","decodeURIComponent","sendFormData","submission","formdata","FormData","append","serializedData","extend","ajaxSettings","contentType","processData","cache","method","uploadProgress","createXhr","xhr","upload","addEventListener","event","percent","position","loaded","total","lengthComputable","Math","ceil","beforeSend","formData","ajax","sendAjax","uploadAttributes","hasOwn","isGet","addSubmitterFields","submitterFields","addCsrfField","forms","origin","csrf_token","csrf_param","posts","property","href","location","protocol","host","setFormAttribute","getDoc","frame","doc","contentWindow","err","contentDocument","readStatus","status","statusText","readResponse","retry","errMsg","isXml","XMLDocument","isXMLDoc","body","innerHTML","docRoot","documentElement","responseText","responseXML","getResponseHeader","header","readDocument","dt","scr","textarea","ta","pre","b","textContent","innerText","readEmbedded","ct","xml","nodeName","error","dataFilter","JSON","parse","globalEval","httpData","createLifecycle","g","timeoutHandle","callbackProcessed","deferred","Deferred","aborted","getAllResponseHeaders","setRequestHeader","abort","done","rejection","textStatus","stop","reject","trigger","complete","endGlobalEvents","active","clearTimeout","release","settle","failure","resolve","succeed","start","global","fail","startTimer","onTimeout","timeout","stopTimer","createIframeTransport","hasProp","frameCount","fileUploadIframe","ownerDocument","$body","$io","iframeTarget","each","nameWindow","io","setAttribute","iframeSrc","css","createFrame","Date","getTime","life","execCommand","remove","frameHooks","domCheckCount","checkState","state","readyState","cb","doSubmit","saved","saveAttributes","mp","skipEncodingOverride","setUploadAttributes","extraInputs","added","addHiddenInput","appendTo","isPlainObject","single","f","addExtraInputs","root","contains","notInDocument","attachEvent","listen","submitForm","restoreAttributes","detachEvent","removeEventListener","unlisten","post","forceSync","jqxhr","elements","prop","removeAttr","enableControls","closeKeepAlive","createSubmission","serialization","refuse","extraQuery","optionsData","requestFormat","query","pairs","at","decodeQuery","queryPairs","defineKey","object","defineProperty","enumerable","writable","configurable","callbackList","callback","isArray","callEach","callbacks","args","prepare","$set","action","trim","URL","withDefaults","defaultType","veto","beforeSerialize","qx","beforeSubmit","resolved","resolveMethod","extra","stringify","jsonBody","q","toUpperCase","hashAt","base","encode","$form","deliver","resetForm","clearForm","includeHidden","successes","jqXHR","successArguments","replaceTarget","$target","merge","errors","completes","chooseTransport","hasFileInputs","add","multipart","attribute","fileAPI","shouldUseFrame","transport","iframe","steps","transports","attr2","removeData","k","formToArray","formSerialize","fieldSerialize","successful","t","checked","isSuccessful","clearFields","clearInputs","re","tag","replaceWith","clone","defaultChecked","defaultValue","select","parents","multiple","defaultSelected","find","forEl","htmlFor","getElementById","enable","parent"],"mappings":";;;;;;;;;;;;;;;;;;;;;kRAMA,IAAIA,EAAS,CAAC,kBAAmB,cAAe,UAAW,QAGvDC,EAAYC,SAASC,cAAc,QAEvC,SAASC,EAAeC,GACtB,IAAK,IAAIC,EAAI,EAAGA,EAAIN,EAAOO,OAAQD,IAAK,CACtC,IAAIE,EAAQC,OAAOT,EAAOM,IACtBI,EAAaF,GAASG,OAAOC,yBAAyBJ,EAAMK,UAAWR,GAE3E,GAAIK,EACF,OAAOA,CAEX,CAEA,OAAO,IACT,CAOO,SAASI,EAAWC,EAAMV,GAC/B,IAAIK,EAAaN,EAAeC,GAEhC,IACE,OAAOK,EAAWM,IAAIC,KAAKF,EAC7B,CAAE,MAAOG,GACP,OAAOH,EAAKV,EACd,CACF,CAMO,SAASc,EAAeJ,EAAMV,GACnC,IAAIK,EAAaN,EAAeC,GAGhC,OAFaK,EAAaA,EAAWU,MAAQnB,EAAUI,IAEzCgB,MAAMN,EAAMO,MAAMT,UAAUU,MAAMN,KAAKO,UAAW,GAClE,CAGO,SAASC,EAAQC,GACtB,IAAIrB,EAAOS,EAAWY,EAAI,WAE1B,MAAuB,iBAATrB,EAAoBA,EAAKsB,cAAgB,EACzD,CAGO,SAASC,EAAUC,GACxB,OAAwC,IAAjCf,EAAWe,EAAM,WAC1B,CAIO,SAASC,EAAiBJ,GAC/B,GAAIA,EAAGK,aAAejB,EAAWY,EAAI,cACnC,MAAM,IAAIM,MACR,kGAGN,CAGO,SAASC,EAAaP,EAAIQ,GAC/B,IAAK,IAAIL,EAAOH,EAAIG,EAAMA,EAAOf,EAAWe,EAAM,cAChD,GAAIK,EAAMC,QAAQV,EAAQI,KAAU,EAClC,OAAOA,EAI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H,GAAGkG,SAAW,SAAUkU,GAKxB,YAJsB,IAAXA,IACTA,GAAS,GAGJ7W,KAAKqO,KAAK,WACf,IAAI6H,EAAIlW,KAAK9D,KAEb,GAAU,aAANga,GAA0B,UAANA,EACtBlW,KAAKmW,QAAUU,OACV,GAAsB,WAAlBlc,EAAQqF,MAAoB,CACrC,IAAIE,EAAOyD,EAAE3D,MAAMsX,OAAO,UAEtBT,GAAU3W,EAAK,IAAuB,eAAjBA,EAAK,GAAGhE,MAE/BgE,EAAK+W,KAAK,UAAUtU,UAAS,GAG/B3C,KAAK2C,SAAWkU,CAClB,CACF,EACF,EAGAlT,EAAElH,GAAGY,WAAWC,OAAQ,CACzB,CAlcD,CAkcGtB"} \ No newline at end of file diff --git a/dist/jquery.form.mjs b/dist/jquery.form.mjs index 1e7b504..954b874 100644 --- a/dist/jquery.form.mjs +++ b/dist/jquery.form.mjs @@ -1,6 +1,6 @@ /*! * jQuery Form Plugin - * version: 4.4.0 + * version: 4.5.0 * Requires jQuery v1.7.2 or later * Project repository: https://github.com/jquery-form/form @@ -23,1116 +23,2296 @@ import jQuery from 'jquery'; export { default } from 'jquery'; -(function ($) { +// Form members: the properties and methods the plugin reads or calls on a form. A control named +// like a member (elements, setAttribute) shadows that member on the form itself, so members are +// read through the DOM prototypes, which a control cannot shadow. - /* - Usage Note: - ----------- - Do not use both ajaxSubmit and ajaxForm on the same form. These - functions are mutually exclusive. Use ajaxSubmit if you want - to bind your own submit handler to the form. For example, +// The prototype chain of a form, nearest first. Looked up on every call: old browsers have no +// DOM prototypes, and tests remove them. +var owners = ["HTMLFormElement", "HTMLElement", "Element", "Node"]; - $(document).ready(function() { - $('#myForm').on('submit', function(e) { - e.preventDefault(); // <-- important - $(this).ajaxSubmit({ - target: '#output' - }); - }); - }); +// A form no control can shadow, for methods when the DOM has no prototypes to read them from. +var plainForm = document.createElement("form"); - Use ajaxForm when you want the plugin to manage all the event binding - for you. For example, +function findDescriptor(name) { + for (var i = 0; i < owners.length; i++) { + var owner = window[owners[i]]; + var descriptor = owner && Object.getOwnPropertyDescriptor(owner.prototype, name); - $(document).ready(function() { - $('#myForm').ajaxForm({ - target: '#output' - }); - }); + if (descriptor) { + return descriptor; + } + } - You can also use ajaxForm with delegation (requires jQuery v1.7+), so the - form does not have to exist when you invoke ajaxForm: + return null; +} - $('#myForm').ajaxForm({ - delegation: true, - target: '#output' - }); +/** + * Reads a member of a form through its prototype getter. + * Falls back to the plain property without DOM prototypes, or on an element the getter does not + * accept (such as a fieldset for `elements`). + */ +function formMember(form, name) { + var descriptor = findDescriptor(name); - When using ajaxForm, the ajaxSubmit function will be invoked for you - at the appropriate time. - */ + try { + return descriptor.get.call(form); + } catch (e) { + return form[name]; + } +} - var rCRLF = /\r?\n/g; +/** + * Calls a method of a form through its prototype, or through an unshadowed form without DOM + * prototypes. + */ +function callFormMethod(form, name) { + var descriptor = findDescriptor(name); + var method = descriptor ? descriptor.value : plainForm[name]; + + return method.apply(form, Array.prototype.slice.call(arguments, 2)); +} + +// Nodes such as the document and text nodes have no tag name (#600). +function tagName(el) { + var name = formMember(el, "tagName"); + + return typeof name === "string" ? name.toLowerCase() : ""; +} + +// Elements only: the subject of formToArray may also be the document or a plain object. +function isElement(node) { + return formMember(node, "nodeType") === 1; +} + +// A control named parentNode makes every parentNode walk (jQuery's trigger and closest among +// them) cycle between the form and the control. +function assertRealParent(el) { + if (el.parentNode !== formMember(el, "parentNode")) { + throw new Error( + 'jquery.form: a form control named "parentNode" hides the form\'s parentNode; rename the control' + ); + } +} - /** - * Feature detection - */ - var feature = {}; +// The element itself or its nearest ancestor with one of the tag names, through the real tree. +function closestByTag(el, names) { + for (var node = el; node; node = formMember(node, "parentNode")) { + if (names.indexOf(tagName(node)) >= 0) { + return node; + } + } - feature.fileapi = $('').get(0).files !== undefined; - feature.formdata = typeof window.FormData !== "undefined"; + return null; +} - var hasProp = !!$.fn.prop; - // Called through the prototype: an extraData key or a form field may be named hasOwnProperty. - var hasOwn = Object.prototype.hasOwnProperty; +// The submitter: the button that submitted a form, captured from ajaxForm's clicks. It is kept in +// a private store and cleared shortly after the click. The form's clk, clk_x and clk_y properties +// are still written for pages that read them, and read when the store has none. + +var storeKey = "jqFormSubmitter"; - // A control named like a form member (elements, setAttribute) shadows that member on the form, - // so forms are read and changed through members a control cannot shadow. - var plainForm = document.createElement("form"); +// Writes a property on the form; a control with that name makes it read-only. +function setExpando(form, name, value) { + try { + form[name] = value; + } catch (ignore) { + // the control keeps the name; the store has the submitter + } +} + +// A property the page set on the form, never a control of the form with that name. +function expando(form, name) { + var value = form[name]; + var els = formMember(form, "elements"); - // Resolves both URLs through anchors, as jQuery does for crossDomain, so IE's anchor quirks - // apply to both sides of the comparison. - function isSameOrigin(url) { - var origin = document.createElement("a"); - var target = document.createElement("a"); + return els && value && els.namedItem(name) === value ? undefined : value; +} - origin.href = window.location.href; - target.href = url; - // IE fills in the host of a relative URL only once the resolved href is assigned back - target.href = target.href; // eslint-disable-line no-self-assign +// Records a submitter for a form until the click window ends. +function record(form, el, x, y) { + jQuery.data(form, storeKey, { el: el, x: x, y: y }); + setExpando(form, "clk", el); - return origin.protocol + "//" + origin.host === target.protocol + "//" + target.host; + if (el.type === "image") { + setExpando(form, "clk_x", x); + setExpando(form, "clk_y", y); } - // Nodes such as the document and text nodes have no tag name (#600). - function tagName(el) { - return typeof el.tagName === "string" ? el.tagName.toLowerCase() : ""; + // clear form vars + setTimeout(function () { + jQuery.data(form, storeKey, null); + setExpando(form, "clk", null); + setExpando(form, "clk_x", null); + setExpando(form, "clk_y", null); + }, 100); +} + +// The clicked point of an image button, relative to the image. +function imagePoint(e, target) { + if (typeof e.offsetX !== "undefined") { + return [e.offsetX, e.offsetY]; } - function formElements(form) { - var proto = window.HTMLFormElement && window.HTMLFormElement.prototype; - var descriptor = proto && Object.getOwnPropertyDescriptor(proto, "elements"); + if (typeof jQuery.fn.offset === "function") { + var offset = jQuery(target).offset(); - try { - return descriptor.get.call(form); - } catch (e) { - // no DOM prototype accessors, or another element with controls such as a fieldset - return form.elements; - } + return [e.pageX - offset.left, e.pageY - offset.top]; } - // attr2 uses prop when it can but checks the return type for - // an expected string. This accounts for the case where a form - // contains inputs with names like "action" or "method"; in those - // cases "prop" returns the element - $.fn.attr2 = function () { - if (!hasProp) { - return this.attr.apply(this, arguments); - } + return [e.pageX - target.offsetLeft, e.pageY - target.offsetTop]; +} - var val = this.prop.apply(this, arguments); +/** + * Records the submit or image button a click event reached, for the form it belongs to. + */ +function captureSubmitter(e) { + // the clicked control, or the button around the clicked content (ex: a span within a button) + var target = closestByTag(e.target, ["button", "input"]); - if ((val && val.jquery) || typeof val === "string") { - return val; - } + // the type property, unlike the attribute, is "submit" for a button without a type (#588) + if (!target || (target.type !== "submit" && target.type !== "image")) { + return; + } - return this.attr.apply(this, arguments); - }; + var form = target.form; - /** - * ajaxSubmit() provides a mechanism for immediately submitting - * an HTML form using AJAX. - * - * @param {object|string} options jquery.form.js parameters or custom url for submission - * @param {object} data extraData - * @param {string} dataType ajax dataType - * @param {function} onSuccess ajax success callback function - */ - $.fn.ajaxSubmit = function (options, data, dataType, onSuccess) { - // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) - if (!this.length) { - log("ajaxSubmit: skipping submit process - no element selected"); + if (!form) { + // a submit control that belongs to no form + return; + } - return this; - } + var point = target.type === "image" ? imagePoint(e, target) : []; - var method, - action, - url, - isMsie, - iframeSrc, - $form = this; - - if (typeof options === "function") { - options = { success: options }; - } else if (typeof options === "string" || (options === false && arguments.length > 0)) { - options = { - url: options, - data: data, - dataType: dataType, - }; + record(form, target, point[0], point[1]); +} - if (typeof onSuccess === "function") { - options.success = onSuccess; - } - } else if (typeof options === "undefined") { - options = {}; - } +/** + * Records the submitter a submit event names (SubmitEvent.submitter), when no click was captured. + * An image submitter gets the point 0,0, as native submission sends it without a click. + */ +function captureEventSubmitter(e, form) { + var el = e.originalEvent && e.originalEvent.submitter; - method = options.method || options.type || this.attr2("method"); - action = options.url || this.attr2("action"); + if (el && !submitterOf(form)) { + record(form, el, 0, 0); + } +} - url = typeof action === "string" ? action.trim() : ""; - // clean url (don't include hash value); an action that is only a fragment means this page - url = url.split("#")[0] || window.location.href.split("#")[0]; - // IE requires javascript:false in https, but this breaks chrome >83 and goes against spec. - // Instead of using javascript:false always, let's only apply it for IE. - isMsie = /(MSIE|Trident)/.test(navigator.userAgent || ""); - iframeSrc = isMsie && /^https/i.test(document.URL) ? "javascript:false" : "about:blank"; // eslint-disable-line no-script-url +/** + * The form's submitter as { el, x, y } (x and y for an image button), or null. + */ +function submitterOf(form) { + if (!form) { + return null; + } - options = $.extend( - true, - { - url: url, - success: $.ajaxSettings.success, - type: method || $.ajaxSettings.type, - iframeSrc: iframeSrc, - }, - options - ); + var stored = jQuery.data(form, storeKey); - // hook for manipulating the form data before it is extracted; - // convenient for use with rich editors like tinyMCE or FCKEditor - var veto = {}; + if (stored) { + return stored; + } - this.trigger("form-pre-serialize", [this, options, veto]); + var el = expando(form, "clk"); - if (veto.veto) { - log("ajaxSubmit: submit vetoed via form-pre-serialize trigger"); + return el ? { el: el, x: expando(form, "clk_x"), y: expando(form, "clk_y") } : null; +} - return this; +/** + * The submitter's fields for a post that adds them itself (the iframe upload), as name → value. + */ +function submitterFields(form) { + var fields = {}; + var sub = submitterOf(form); + var el = sub && sub.el; + + if (el && el.name && !el.disabled) { + fields[el.name] = el.value; + if (el.type === "image") { + fields[el.name + ".x"] = sub.x; + fields[el.name + ".y"] = sub.y; } + } - // provide opportunity to alter form data before it is serialized - if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { - log("ajaxSubmit: submit aborted via beforeSerialize callback"); + return fields; +} - return this; - } +/** + * The form's submitter element, or null. + */ +function submitterElement(form) { + var sub = submitterOf(form); - var traditional = options.traditional; + return sub ? sub.el : null; +} - if (typeof traditional === "undefined") { - traditional = $.ajaxSettings.traditional; - } +// Debug logging, switched on by $.fn.ajaxSubmit.debug. The flag is read on every call, so it can +// be turned on after the plugin loads. +function log() { + if (!jQuery.fn.ajaxSubmit.debug) { + return; + } - var elements = []; - var qx, - a = this.formToArray(options.semantic, elements, options.filtering); + var msg = "[jquery.form] " + Array.prototype.join.call(arguments, ""); - if (options.data) { - var optionsData = typeof options.data === "function" ? options.data(a) : options.data; + if (window.console && window.console.log) { + window.console.log(msg); + } else if (window.opera && window.opera.postError) { + window.opera.postError(msg); + } +} - options.extraData = optionsData; - qx = $.param(optionsData, traditional); - } +var warned = {}; - // give pre-submit callback an opportunity to abort the submit - if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { - log("ajaxSubmit: submit aborted via beforeSubmit callback"); +/** + * A deprecation warning: console.warn, only while debug is on, once per id per page. The message + * names the replacement; the warning adds that the feature is removed in 5.0. + */ +function deprecate(id, message) { + if (!jQuery.fn.ajaxSubmit.debug || warned[id]) { + return; + } - return this; - } + warned[id] = true; - // fire vetoable 'validate' event - this.trigger("form-submit-validate", [a, this, options, veto]); - if (veto.veto) { - log("ajaxSubmit: submit vetoed via form-submit-validate trigger"); + if (window.console && typeof window.console.warn === "function") { + window.console.warn("[jquery.form] " + message + " (removed in 5.0)"); + } +} + +// True for a jQuery version string older than 3.5. +function beforeJQuery35(version) { + var parts = String(version).split("."); + var major = Number(parts[0]); + + return major < 3 || (major === 3 && Number(parts[1]) < 5); +} + +// 5.0 needs jQuery 3.5 or later: warned on the first ajaxSubmit or ajaxForm, given jQuery's version. +function deprecateOldJQuery(version) { + if (beforeJQuery35(version)) { + deprecate( + "jquery", + "support for jQuery " + version + " is deprecated, 5.0 needs jQuery 3.5 or later" + ); + } +} - return this; - } +// The arguments ajaxSubmit and ajaxForm accept in place of an options object. - var q = $.param(a, traditional); +/** + * Turns the (url, data, dataType, success) shorthand into options. A url of false is kept as + * the url; anything else is returned as given. + */ +function shorthandOptions(options, data, dataType, onSuccess) { + if (typeof options !== "string" && options !== false) { + return options; + } - if (qx) { - q = q ? q + "&" + qx : qx; - } + var result = { url: options, data: data, dataType: dataType }; - if (options.type.toUpperCase() === "GET") { - // the query goes before any fragment in the url option - var hashAt = options.url.indexOf("#"); - var base = hashAt < 0 ? options.url : options.url.slice(0, hashAt); + if (typeof onSuccess === "function") { + result.success = onSuccess; + } - options.url = - base + (base.indexOf("?") >= 0 ? "&" : "?") + q + options.url.slice(base.length); - options.data = null; // data is null for 'get' - } else { - options.data = q; // data is the query string for 'post' - } + return result; +} - var callbacks = []; +// A copy of options without its url, so the form action is used. +function withoutUrl(options) { + var result = {}; - if (options.resetForm) { - callbacks.push(function () { - $form.resetForm(); - }); + for (var key in options) { + if (key !== "url" && Object.prototype.hasOwnProperty.call(options, key)) { + result[key] = options[key]; } + } - if (options.clearForm) { - callbacks.push(function () { - $form.clearForm(options.includeHidden); - }); - } + return result; +} - // perform a load on the target only if dataType is not provided - if (!options.dataType && options.target) { - var oldSuccess = options.success || function () {}; +/** + * The options ajaxSubmit starts from: a function is the success callback, the shorthand is + * expanded, and no options at all is an empty object. A url of false or "" means the form action. + */ +function submitOptions(options, data, dataType, onSuccess) { + if (typeof options === "function") { + return { success: options }; + } - callbacks.push(function (data, textStatus, jqXHR) { - var successArguments = arguments, - fn = options.replaceTarget ? "replaceWith" : "html", - $target = $(options.target); + options = shorthandOptions(options, data, dataType, onSuccess); - // Only a string response is inserted. jQuery has already parsed a JSON or XML response, - // and inserting it would parse each of its strings as HTML. - if (typeof data === "string") { - $target[fn](data); - } else { - log("target: the response was parsed by jQuery, so it is not inserted"); - } + if (typeof options === "undefined") { + return {}; + } - $target.each(function () { - oldSuccess.apply(this, successArguments); - }); - }); - } else if (options.success) { - if (Array.isArray(options.success)) { - $.merge(callbacks, options.success); - } else { - callbacks.push(options.success); - } + return options.url === false || options.url === "" ? withoutUrl(options) : options; +} + +/** + * jQuery treats `context` as a flat option: after a deep merge, the settings get back the + * caller's own object from the last source that has one, so `this` in callbacks is that object. + */ +function keepContext(settings, sources) { + for (var i = 0; i < sources.length; i++) { + if (sources[i].context !== undefined) { + settings.context = sources[i].context; } + } - options.success = function (data, status, xhr) { - // jQuery 1.4+ passes xhr as 3rd arg - var context = options.context || this; // jQuery 1.4+ supports scope context + return settings; +} - for (var i = 0, max = callbacks.length; i < max; i++) { - callbacks[i].apply(context, [data, status, xhr || $form, $form]); - } - }; +// ajaxForm binding: the submit and click handlers that send a form through ajaxSubmit. The +// handlers look up $.fn.ajaxSubmit when they run, so a replacement installed later is used. - if (options.error) { - var oldError = options.error; +// Sends the submit event's form with ajaxSubmit, unless an earlier handler cancelled it. +function submitWith(e, options) { + if (!e.isDefaultPrevented()) { + // if event has been canceled, don't proceed + e.preventDefault(); + // the form is found through the real tree: a control named nodeType misleads jQuery's closest + var form = closestByTag(e.target, ["form"]); - options.error = function (xhr, status, error) { - var context = options.context || this; + // a button outside the form (form attribute), or requestSubmit(button), sends no click here + captureEventSubmitter(e, form); + jQuery(form).ajaxSubmit(options); // #365 + } +} + +function doAjaxSubmit(e) { + submitWith(e, e.data); +} + +function captureSubmittingElement(e) { + /* jshint validthis:true */ + assertRealParent(this); + captureSubmitter(e); +} + +// An empty selection: queued until the DOM is ready (old jQuery keeps the selector), or dropped. +function bindLater($sel, options) { + var o = { s: $sel.selector, c: $sel.context }; + + if (!jQuery.isReady && o.s) { + log("DOM not ready, queuing ajaxForm"); + deprecate( + "queue", + "queuing ajaxForm until the DOM is ready is deprecated, call ajaxForm inside $(fn) " + + 'or use delegation: ""' + ); + jQuery(function () { + jQuery(o.s, o.c).ajaxForm(options); + }); - oldError.apply(context, [xhr, status, error, $form]); - }; - } + return $sel; + } - if (options.complete) { - var oldComplete = options.complete; + // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() + log("terminating; zero elements found by selector" + (jQuery.isReady ? "" : " (DOM not ready)")); - options.complete = function (xhr, status) { - var context = options.context || this; + return $sel; +} - oldComplete.apply(context, [xhr, status, $form]); - }; - } +// delegation: true on jQuery 3 and later, where the selection has no selector: always warned, +// debug or not, once per ajaxForm call. +function warnUnscoped() { + var console = window.console || {}; - // are there files to upload? + if (typeof console.warn === "function") { + console.warn( + "[jquery.form] delegation: true binds every form on the page on jQuery 3 and later; " + + 'pass a selector instead, e.g. delegation: "form.ajax"' + ); + } +} - // [value] (issue #113), also see comment: - // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219 - var fileInputs = $("input[type=file]:enabled", this).filter(function () { - return $(this).val() !== ""; - }); - var hasFileInputs = fileInputs.length > 0; - var mp = "multipart/form-data"; - var multipart = $form.attr("enctype") === mp || $form.attr("encoding") === mp; - var fileAPI = feature.fileapi && feature.formdata; +function bindDelegated($sel, options) { + if ($sel.selector === undefined) { + warnUnscoped(); + } - log("fileAPI :" + fileAPI); + jQuery(document) + .off("submit.form-plugin", $sel.selector, doAjaxSubmit) + .off("click.form-plugin", $sel.selector, captureSubmittingElement) + .on("submit.form-plugin", $sel.selector, options, doAjaxSubmit) + .on("click.form-plugin", $sel.selector, options, captureSubmittingElement); - var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI; - var jqxhr; + return $sel; +} - // options.iframe allows user to force iframe mode - // 06-NOV-09: now defaulting to iframe mode if file input is detected - if (options.iframe !== false && (options.iframe || shouldUseFrame)) { - // hack to fix Safari hang (thanks to Tim Molendijk for this) - // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d - if (options.closeKeepAlive) { - $.get(options.closeKeepAlive, function () { - jqxhr = fileUploadIframe(); - }); - } else { - jqxhr = fileUploadIframe(); - } - } else if ((hasFileInputs || multipart) && fileAPI) { - jqxhr = fileUploadXhr(a); - } else { - jqxhr = $.ajax(options); - } +// The element itself or its nearest ancestor that matches the selector. The walk never reads a +// parentNode a control can hide (jQuery's delegated walk does, and cycles on such a form). +function closestMatch(el, selector) { + if (!isElement(el)) { + return null; + } - $form.removeData("jqxhr").data("jqxhr", jqxhr); + if (window.Element && Element.prototype.closest) { + return Element.prototype.closest.call(el, selector); + } - // clear element array - for (var k = 0; k < elements.length; k++) { - elements[k] = null; + for (var node = el; node && isElement(node); node = formMember(node, "parentNode")) { + if (jQuery(node).is(selector)) { + return node; } + } - // fire 'notify' event - this.trigger("form-submit-notify", [this, options]); + return null; +} - return this; +// The document handlers bound for each delegation selector, keyed by "s" + selector. +var delegated = {}; - // utility fn for deep serialization - function deepSerialize(extraData) { - var param = $.param(extraData, traditional); - var serialized = param ? param.split("&") : []; - var len = serialized.length; - var result = []; - var i, part; - - for (i = 0; i < len; i++) { - // #252; undo param space replacement - serialized[i] = serialized[i].replace(/\+/g, " "); - part = serialized[i].split("="); - // #278; use array instead of object storage, favoring array serializations - result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]); - } +function unbindSelector(selector) { + var handlers = delegated["s" + selector]; - return result; - } + if (handlers) { + jQuery(document) + .off("submit.form-plugin", handlers.submit) + .off("click.form-plugin", handlers.click); + delete delegated["s" + selector]; + } +} - // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz) - function fileUploadXhr(a) { - var formdata = new FormData(); +// delegation: "": one handler pair on the document, scoped to the selector. +function bindSelector($sel, selector, options) { + if (!selector) { + throw new Error("jquery.form: delegation needs a selector, or true"); + } - for (var i = 0; i < a.length; i++) { - formdata.append(a[i].name, a[i].value); + var handlers = { + submit: function (e) { + if (closestMatch(e.target, selector)) { + submitWith(e, options); + } + }, + click: function (e) { + if (closestMatch(e.target, selector)) { + captureSubmitter(e); } + }, + }; - if (options.extraData) { - var serializedData = deepSerialize(options.extraData); + unbindSelector(selector); + delegated["s" + selector] = handlers; + jQuery(document) + .on("submit.form-plugin", handlers.submit) + .on("click.form-plugin", handlers.click); - for (i = 0; i < serializedData.length; i++) { - formdata.append(serializedData[i][0], serializedData[i][1]); - } - } + return $sel; +} - options.data = null; +// Passed by ajaxForm's own rebind: unbind the selection only, never the document handlers. +var selectionOnly = {}; - var s = $.extend(true, {}, $.ajaxSettings, options, { - contentType: false, - processData: false, - cache: false, - type: method || "POST", - }); +/** + * ajaxForm() binds the selected forms so a submit is sent with ajaxSubmit, with the clicked + * submit button (and image coordinates) included. The options work as for ajaxSubmit. + */ +function ajaxForm(options, data, dataType, onSuccess) { + deprecateOldJQuery(jQuery.fn.jquery); + options = shorthandOptions(options, data, dataType, onSuccess) || {}; - if (options.uploadProgress) { - // workaround because jqXHR does not expose upload property - s.xhr = function () { - var xhr = $.ajaxSettings.xhr(); - - if (xhr.upload) { - xhr.upload.addEventListener( - "progress", - function (event) { - var percent = 0; - var position = event.loaded || event.position; /* event.position is deprecated */ - var total = event.total; - - if (event.lengthComputable) { - percent = Math.ceil((position / total) * 100); - } - - options.uploadProgress(event, position, total, percent); - }, - false - ); - } + if (typeof options.delegation === "string") { + return bindSelector(this, options.delegation, options); + } - return xhr; - }; - } + options.delegation = options.delegation && typeof jQuery.fn.on === "function"; - s.data = null; + if (!options.delegation && this.length === 0) { + return bindLater(this, options); + } - var beforeSend = s.beforeSend; + if (options.delegation) { + return bindDelegated(this, options); + } - s.beforeSend = function (xhr, o) { - // Send FormData() provided by user - if (options.formData) { - o.data = options.formData; - } else { - o.data = formdata; - } + if (options.beforeFormUnbind) { + options.beforeFormUnbind(this, options); + } - if (beforeSend) { - beforeSend.call(this, xhr, o); - } - }; + return this.ajaxFormUnbind(selectionOnly) + .on("submit.form-plugin", options, doAjaxSubmit) + .on("click.form-plugin", options, captureSubmittingElement); +} - return $.ajax(s); - } - - // private function for handling file uploads (hat tip to YAHOO!) - function fileUploadIframe(a) { - var form = $form[0], - el, - i, - s, - g, - id, - $io, - io, - xhr, - sub, - n, - timeoutHandle, - callbackProcessed; - var deferred = $.Deferred(); - - // #341 - deferred.abort = function (status) { - xhr.abort(status); - }; +/** + * ajaxFormUnbind() removes the handlers ajaxForm bound on the selection and every delegated + * binding on the document. ajaxFormUnbind(selector) removes only that delegation selector. + */ +function ajaxFormUnbind(selector) { + if (typeof selector === "string") { + unbindSelector(selector); - // ensure that every serialized input is still enabled - for (i = 0; i < elements.length; i++) { - el = $(elements[i]); - if (hasProp) { - el.prop("disabled", false); - } else { - el.removeAttr("disabled"); - } - } + return this; + } - s = $.extend(true, {}, $.ajaxSettings, options); - s.context = s.context || s; - id = "jqFormIO" + new Date().getTime(); - var ownerDocument = form.ownerDocument; - var $body = $form.closest("body"); - - if (s.iframeTarget) { - $io = $(s.iframeTarget, ownerDocument); - n = $io.attr2("name"); - if (!n) { - $io.attr2("name", id); - } else { - id = n; - } + if (selector !== selectionOnly) { + delegated = {}; + jQuery(document).off("submit.form-plugin click.form-plugin"); + } + + return this.off("submit.form-plugin click.form-plugin"); +} + +/** + * An attribute of a form, or undefined when it is absent, as jQuery's attr returns it. The + * subject may also be the document or a plain object, read through jQuery. + */ +function formAttribute(form, name) { + if (!isElement(form)) { + return jQuery(form).attr(name); + } + + var value = callFormMethod(form, "getAttribute", name); + + return value === null ? undefined : value; +} + +// Successful controls: which controls of a form are sent, and as which name/value fields +// (https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constructing-the-form-data-set). + +// Line breaks, sent as CRLF +var rLineBreak = /\r\n|\r|\n/g; +var rCR = /\r/g; + +// Listed form elements that are never submitted. +var rUnsubmittable = /^(?:fieldset|object|output)$/; + +/** + * Whether a control or option is disabled, also through a disabled fieldset or optgroup. Without + * selector matching, only its own disabled property is read. + */ +function isDisabled(el) { + return typeof el.matches === "function" ? el.matches(":disabled") : !!el.disabled; +} + +/** + * The successful-control rule: whether a control is sent. `submitter` is the button that + * submitted the control's form; other submit and image buttons of a form are not sent. + */ +function isSuccessful(el, submitter) { + var t = el.type; + + if (!el.name || isDisabled(el) || t === "reset" || t === "button") { + return false; + } + + if (t === "checkbox" || t === "radio") { + return !!el.checked; + } + + if (t === "submit" || t === "image") { + return !el.form || submitter === el; + } + + return tagName(el) !== "select" || el.selectedIndex !== -1; +} + +// The value of a select: the selected option's value for one, a list for several. +function selectValue(el) { + var index = el.selectedIndex; + + if (index < 0) { + return null; + } + + var a = [], + ops = el.options; + var one = el.type === "select-one"; + var max = one ? index + 1 : ops.length; + + for (var i = one ? index : 0; i < max; i++) { + var op = ops[i]; + + if (op.selected && !isDisabled(op)) { + var v = op.value; + + if (!v) { + // extra pain for IE... + v = + op.attributes && op.attributes.value && !op.attributes.value.specified + ? op.text + : op.value; + } + + if (one) { + return v; + } + + a.push(v); + } + } + + return a; +} + +/** + * The value of a control, whether or not it is successful: a list for a multiple select, null + * for a select with nothing selected, otherwise a string with CRLF line breaks (a lone CR or LF + * included). + */ +function valueOf(el) { + if (tagName(el) === "select") { + return selectValue(el); + } + + var v = jQuery(el).val(); + var raw = el.value; + + // jQuery before 4.0 drops carriage returns from .val(); read them from the value itself + if (typeof raw === "string" && raw.replace(rCR, "") === v) { + v = raw; + } + + return v.replace(rLineBreak, "\r\n"); +} + +/** + * The fields as a urlencoded body sends them: a selected file as its name. + */ +function urlencodedFields(fields) { + return jQuery.map(fields, function (field) { + return field.type === "file" && typeof field.value !== "string" + ? { name: field.name, value: field.value.name } + : field; + }); +} + +/** + * The serialization steps. `feature` holds what the entry detected at load (fileapi). + */ +function createSuccessfulControls(feature) { + var $ = jQuery; + + // #386; inputs that name the form in their form attribute, other than the candidates found. + // A form only gets the ones it owns. + function outsideControls(formId, els, owner) { + // hat tip @thet; the id is compared, never built into a selector + return $(":input[form]") + .filter(function () { + return ( + this.getAttribute("form") === formId && + (!owner || this.form === owner) && + $.inArray(this, els) < 0 + ); + }) + .get(); + } + + // A descendant of a form is a candidate unless it is a control another form owns. + function ownedBy(els, owner) { + return $.grep(els, function (el) { + return typeof el.form === "undefined" || el.form === owner; + }); + } + + /** + * The candidate controls of a form, in order: its elements, or every descendant it owns in + * semantic mode, then the outside controls it owns that name it. + */ + function controlsOf(form, semantic) { + var formId = formAttribute(form, "id"); + var els = formMember(form, "elements"); + + if (semantic || typeof els === "undefined") { + // the document is not an element; it has its own getElementsByTagName + els = isElement(form) + ? callFormMethod(form, "getElementsByTagName", "*") + : form.getElementsByTagName("*"); + } + + els = $.makeArray(els); + + // the subject may also be a fieldset, the document or another container + var owner = tagName(form) === "form" ? form : null; + + if (semantic && owner) { + els = ownedBy(els, owner); + } + + // FinesseRus: in non-IE browsers outside fields are already included in form.elements. + if (formId && (semantic || /(Edge|Trident)\//.test(navigator.userAgent))) { + els = els.concat(outsideControls(formId, els, owner)); + } + + return els; + } + + // The fields of a control's value, or null when the control is not sent. + function fieldsOf(el) { + var n = el.name; + // read at call time, so a page that replaces $.fieldValue changes what is sent + var v = $.fieldValue(el, true); + + if (v && v.constructor === Array) { + return $.map(v, function (value) { + return { name: n, value: value }; + }); + } + + if (feature.fileapi && el.type === "file") { + var files = el.files; + + // #180: an empty field when no file is selected + return files.length + ? $.map(files, function (file) { + return { name: n, value: file, type: el.type }; + }) + : [{ name: n, value: "", type: el.type }]; + } + + if (v === null || typeof v === "undefined") { + return null; + } + + return [{ name: n, value: v, type: el.type, required: el.required }]; + } + + // The clicked image's value and coordinates. + function imageFields(sub, input, type) { + var n = input.name; + var value = { name: n, value: $(input).val() }; + + if (type) { + value.type = type; + } + + return [value, { name: n + ".x", value: sub.x }, { name: n + ".y", value: sub.y }]; + } + + // Adds one candidate control's fields, and the control when it has a value to send. + function addCandidate(collected, form, el, semantic) { + if (!el.name || isDisabled(el) || rUnsubmittable.test(tagName(el))) { + return; + } + + var sub = semantic && el.type === "image" && submitterOf(form); + + if (sub) { + // handle image inputs on the fly when semantic == true + if (sub.el === el) { + collected.fields.push.apply(collected.fields, imageFields(sub, el, el.type)); + } + + return; + } + + var own = fieldsOf(el); + + if (own) { + collected.controls.push(el); + collected.fields.push.apply(collected.fields, own); + } + } + + // input type=='image' are not found in elements array! handle it here + function addClickedImage(collected, form) { + var sub = submitterOf(form); + var input = sub && $(sub.el)[0]; + + if (input && input.name && !isDisabled(input) && input.type === "image") { + collected.fields.push.apply(collected.fields, imageFields(sub, input)); + } + } + + /** + * The fields of a form, as formToArray returns them, and the controls they came from. + */ + function collect(form, semantic, filtering) { + var collected = { fields: [], controls: [] }; + + if (!form) { + return collected; + } + + var els = controlsOf(form, semantic); + + if (typeof filtering === "function") { + els = $.map(els, filtering); + } + + for (var i = 0; i < els.length; i++) { + addCandidate(collected, form, els[i], semantic); + } + + if (!semantic) { + addClickedImage(collected, form); + } + + return collected; + } + + return { + controlsOf: controlsOf, + fieldsOf: fieldsOf, + collect: collect, + }; +} + +// The XMLHttpRequest transports: $.ajax with the encoded fields, or FormData for file uploads. +var $$4 = jQuery; + +// utility fn for deep serialization: [name, value] pairs, as $.param encodes them +function deepSerialize(extraData, traditional) { + var param = $$4.param(extraData, traditional); + var serialized = param ? param.split("&") : []; + var len = serialized.length; + var result = []; + var i, part; + + for (i = 0; i < len; i++) { + // #252; undo param space replacement + serialized[i] = serialized[i].replace(/\+/g, " "); + part = serialized[i].split("="); + // #278; use array instead of object storage, favoring array serializations + result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]); + } + + return result; +} + +/** + * Posts the fields and extraData as FormData, for files with the File API. + * XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz) + */ +function sendFormData(submission) { + var options = submission.options; + var a = submission.fields; + + var formdata = new FormData(); + + for (var i = 0; i < a.length; i++) { + formdata.append(a[i].name, a[i].value); + } + + if (options.extraData) { + var serializedData = deepSerialize(options.extraData, submission.traditional); + + for (i = 0; i < serializedData.length; i++) { + formdata.append(serializedData[i][0], serializedData[i][1]); + } + } + + options.data = null; + + var s = $$4.extend(true, {}, $$4.ajaxSettings, options, { + contentType: false, + processData: false, + cache: false, + type: submission.method || "POST", + }); + + keepContext(s, [$$4.ajaxSettings, options]); + + if (options.uploadProgress) { + // workaround because jqXHR does not expose upload property: wraps the xhr factory, the + // caller's or jQuery's + var createXhr = s.xhr; + + s.xhr = function () { + var xhr = createXhr.call(this); + + if (xhr.upload) { + xhr.upload.addEventListener( + "progress", + function (event) { + var percent = 0; + // event.position is the deprecated name, read only when loaded is missing + var position = event.loaded !== undefined ? event.loaded : event.position; + var total = event.total; + + if (event.lengthComputable) { + percent = Math.ceil((position / total) * 100); + } + + options.uploadProgress(event, position, total, percent); + }, + false + ); + } + + return xhr; + }; + } + + s.data = null; + + var beforeSend = s.beforeSend; + + s.beforeSend = function (xhr, o) { + // Send FormData() provided by user + if (options.formData) { + o.data = options.formData; + } else { + o.data = formdata; + } + + // a veto (false) cancels the upload, as on the other transports + return beforeSend ? beforeSend.call(this, xhr, o) : undefined; + }; + + return $$4.ajax(s); +} + +/** + * Sends the encoded fields with $.ajax. + */ +function sendAjax(submission) { + return $$4.ajax(submission.options); +} + +// The iframe form post: the extra fields (submitter, CSRF, data), the form attributes set while +// posting and restored after, and the native submit. +var $$3 = jQuery; + +// The form attributes an iframe upload changes while it posts. +var uploadAttributes = ["action", "target", "method", "enctype", "encoding"]; + +// Called through the prototype: an extraData key or a form field may be named hasOwnProperty. +var hasOwn = Object.prototype.hasOwnProperty; + +function isGet(method) { + return /^get$/i.test(method); +} + +// Resolves both URLs through anchors, as jQuery does for crossDomain, so IE's anchor quirks +// apply to both sides of the comparison. +function isSameOrigin(url) { + var origin = document.createElement("a"); + var target = document.createElement("a"); + + origin.href = window.location.href; + target.href = url; + // IE fills in the host of a relative URL only once the resolved href is assigned back + target.href = target.href; // eslint-disable-line no-self-assign + + return origin.protocol + "//" + origin.host === target.protocol + "//" + target.host; +} + +/** Adds the clicked submitter (and an image's coordinates) to s.extraData. */ +function addSubmitterFields(s, form) { + // add submitting element to data if we know it + var fields = submitterFields(form); + + for (var n in fields) { + s.extraData = s.extraData || {}; + s.extraData[n] = fields[n]; + } +} + +/** Adds the page's CSRF token to s.extraData when the form is posted to the page's origin. */ +function addCsrfField(s, form, method, forms) { + // Rails CSRF hack (thanks to Yvan Barthelemy); like jquery-ujs, only for the page's origin and + // only when the form is posted, since a get form would put the token in the url + var csrf_token = $$3("meta[name=csrf-token]").attr("content"); + var csrf_param = $$3("meta[name=csrf-param]").attr("content"); + var posts = + !isGet(method) && + (!method || /post/i.test(method) || /post/i.test(forms.property(form, "method"))); + + if (csrf_param && csrf_token && posts && isSameOrigin(s.url)) { + s.extraData = s.extraData || {}; + s.extraData[csrf_param] = csrf_token; + } +} + +function setFormAttribute(form, name, value) { + callFormMethod(form, "setAttribute", name, value); +} + +/** The raw attributes the upload changes, null when absent, to put back exactly (#380). */ +function saveAttributes(form) { + var saved = {}; + + $$3.each(uploadAttributes, function (i, name) { + saved[name] = callFormMethod(form, "hasAttribute", name) + ? callFormMethod(form, "getAttribute", name) + : null; + }); + + return saved; +} + +/** Puts back the attributes saveAttributes recorded, removing those that were absent. */ +function restoreAttributes(form, saved) { + $$3.each(uploadAttributes, function (i, name) { + if (saved[name] === null) { + callFormMethod(form, "removeAttribute", name); + } else { + setFormAttribute(form, name, saved[name]); + } + }); +} + +/** Points the form at the frame `target` with the upload's url, method and encoding. */ +function setUploadAttributes(form, target, method, s, forms) { + var mp = "multipart/form-data"; + + // update form attrs in IE friendly way + setFormAttribute(form, "target", target); + if (!method || /post/i.test(method)) { + setFormAttribute(form, "method", "POST"); + } else if (isGet(method) && !isGet(forms.property(form, "method"))) { + // a form posts natively only with GET or POST; other verbs keep the form's own method + setFormAttribute(form, "method", "GET"); + } + setFormAttribute(form, "action", s.url); + + // ie borks in some cases when setting encoding + if (!s.skipEncodingOverride && (!method || /post/i.test(method))) { + setFormAttribute(form, "encoding", mp); + setFormAttribute(form, "enctype", mp); + } +} + +/** Appends a hidden input per extraData field to the form; each input is pushed onto `added`. */ +function addExtraInputs(form, ownerDocument, extraData, traditional, added) { + // Builds the input with DOM properties: a name is never parsed as HTML. + function addHiddenInput(name, value) { + var input = ownerDocument.createElement("input"); + + input.type = "hidden"; + input.name = name; + added.push($$3(input).val(value).appendTo(form)[0]); + } + + if (extraData) { + for (var n in extraData) { + if (hasOwn.call(extraData, n)) { + // if using the $.param format that allows for multiple values with the same name + if ( + $$3.isPlainObject(extraData[n]) && + hasOwn.call(extraData[n], "name") && + hasOwn.call(extraData[n], "value") + ) { + addHiddenInput(extraData[n].name, extraData[n].value); + } else { + // arrays and objects become one field per value, as $.param sends them (#597) + var single = {}; + + single[n] = extraData[n]; + var fields = deepSerialize(single, traditional); + + for (var f = 0; f < fields.length; f++) { + addHiddenInput(fields[f][0], fields[f][1]); + } + } + } + } + } +} + +/** Submits the form natively, even when a control named submit hides the method. */ +function submitForm(form) { + try { + form.submit(); + } catch (err) { + // just in case form has element with name/id of 'submit' + callFormMethod(form, "submit"); + } +} + +// The iframe response reader: turns the frame's document into the mock xhr's text, XML, status +// and dataType, then parses it as $.ajax would (dataFilter, JSON, script). +var $$2 = jQuery; + +/** The frame's document, or null when the browser denies access to it. */ +function getDoc(frame) { + /* it looks like contentWindow or contentDocument do not + * carry the protocol property in ie8, when running under ssl + * frame.document is the only valid response document, since + * the protocol is know but not on the other two objects. strange? + * "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy + */ + + var doc = null; + + // IE8 cascading access check + try { + if (frame.contentWindow) { + doc = frame.contentWindow.document; + } + } catch (err) { + // IE8 access denied under ssl & missing protocol + log("cannot get iframe.contentWindow document: " + err); + } + + if (doc) { + // successful getting content + return doc; + } + + try { + // simply checking may throw in ie8 under ssl or mismatched protocol + doc = frame.contentDocument ? frame.contentDocument : frame.document; + } catch (err) { + // last attempt + log("cannot get iframe.contentDocument: " + err); + doc = frame.document; + } + + return doc; +} + +/** Parses the response text or XML for the given (lowercase) dataType. */ +function httpData(xhr, type, s) { + // mostly lifted from jq1.4.4 + + var ct = xhr.getResponseHeader("content-type") || "", + xml = (type === "xml" || !type) && ct.indexOf("xml") >= 0, + data = xml ? xhr.responseXML : xhr.responseText; + + if (xml && data.documentElement.nodeName === "parsererror") { + if ($$2.error) { + $$2.error("parsererror"); + } + } + if (s && s.dataFilter) { + data = s.dataFilter(data, type); + } + if (typeof data === "string") { + if ((type === "json" || !type) && ct.indexOf("json") >= 0) { + data = JSON.parse(data); + } else if (type === "script") { + $$2.globalEval(data); + } + } + + return data; +} + +// Copies the status and statusText attributes of an element onto the mock xhr. +function readStatus(xhr, el) { + // support for XHR 'status' & 'statusText' emulation : + xhr.status = Number(el.getAttribute("status")) || xhr.status; + xhr.statusText = el.getAttribute("statusText") || xhr.statusText; +} + +// Fills the mock xhr from the document itself. +function readDocument(doc, xhr, s, isXml) { + var docRoot = doc.body ? doc.body : doc.documentElement; + + xhr.responseText = docRoot ? docRoot.innerHTML : null; + xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; + if (isXml) { + s.dataType = "xml"; + } + xhr.getResponseHeader = function (header) { + // the dataType in lowercase, as $.ajax reads it + var headers = { "content-type": s.dataType && s.dataType.toLowerCase() }; + + return headers[header.toLowerCase()]; + }; + if (docRoot) { + readStatus(xhr, docRoot); + } +} + +// A response embedded in a textarea, or text wrapped in pre or body, replaces responseText. +function readEmbedded(doc, xhr, dt, s) { + var scr = /(json|script|text)/.test(dt); + + if (!scr && !s.textarea) { + return; + } + // see if user embedded response in textarea + var ta = doc.getElementsByTagName("textarea")[0]; + + if (ta) { + xhr.responseText = ta.value; + readStatus(xhr, ta); + } else if (scr) { + // account for browsers injecting pre around json response + var pre = doc.getElementsByTagName("pre")[0]; + var b = doc.getElementsByTagName("body")[0]; + + if (pre) { + xhr.responseText = pre.textContent ? pre.textContent : pre.innerText; + } else if (b) { + xhr.responseText = b.textContent ? b.textContent : b.innerText; + } + } +} + +/** + * Reads and parses the response document into the mock xhr. Returns {status, data, errMsg}, or + * null when `retry()` asks to read the document again later (Opera's untraversable DOM). + */ +function readResponse(doc, xhr, s, retry) { + var status = "success", + data, + errMsg; + + try { + var isXml = /^xml$/i.test(s.dataType) || doc.XMLDocument || $$2.isXMLDoc(doc); + + log("isXml=" + isXml); + + if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) { + // in some browsers (Opera) the iframe DOM is not always traversable when + // the onload callback fires, so we loop a bit to accommodate + if (retry()) { + return null; + } + // let this fall through because server response could be an empty document + } + + readDocument(doc, xhr, s, isXml); + + var dt = (s.dataType || "").toLowerCase(); + + readEmbedded(doc, xhr, dt, s); + + try { + data = httpData(xhr, dt, s); + } catch (err) { + status = "parsererror"; + xhr.error = errMsg = err || status; + } + } catch (err) { + log("error caught: ", err); + status = "error"; + xhr.error = errMsg = err; + } + + return { status: status, data: data, errMsg: errMsg }; +} + +// The iframe upload's lifecycle: the mock xhr and the Deferred, the global ajax events, the +// beforeSend veto, the timeout, abort and settling. +var $$1 = jQuery; + +/** + * Creates the lifecycle of one upload with the merged settings `s`. `frame.stop()` stops the + * frame's load and `frame.release()` removes or resets the frame after the upload. + */ +function createLifecycle(s, frame) { + var g, + timeoutHandle, + callbackProcessed, + deferred = $$1.Deferred(); + + var xhr = { + // mock object + aborted: 0, + responseText: null, + responseXML: null, + status: 0, + statusText: "n/a", + getAllResponseHeaders: function () {}, + getResponseHeader: function () {}, + setRequestHeader: function () {}, + abort: function (status) { + abort(status, [xhr, "aborted", status]); + }, + }; + + // #341 + deferred.abort = function (status) { + xhr.abort(status); + }; + + function done() { + return xhr.aborted || callbackProcessed; + } + + // Completes an aborted upload once and rejects the Deferred with `rejection`. + // `textStatus` replaces the default "timeout"/"aborted" text status. + function abort(status, rejection, textStatus) { + var e = textStatus || (status === "timeout" ? "timeout" : "aborted"); + + if (done()) { + return; + } + + log("aborting upload... " + e); + xhr.aborted = 1; + frame.stop(); + xhr.error = e; + if (s.error) { + s.error.call(s.context, xhr, e, status); + } + deferred.reject.apply(deferred, rejection); + + if (g) { + $$1.event.trigger("ajaxError", [xhr, s, e]); + } + + complete(e); + } + + // The global events that end every upload, cancelled ones included. + function endGlobalEvents() { + if (g) { + $$1.event.trigger("ajaxComplete", [xhr, s]); + } + + if (g && !--$$1.active) { + $$1.event.trigger("ajaxStop"); + } + } + + // The steps every finished or aborted upload ends with, in $.ajax order. + function complete(status) { + if (s.complete) { + s.complete.call(s.context, xhr, status); + } + + endGlobalEvents(); + clearTimeout(timeoutHandle); + + // clean up + setTimeout(function () { + frame.release(); + xhr.responseXML = null; + }, 100); + } + + // A beforeSend veto ends the upload as $.ajax cancels a request: no callbacks, the global + // events end with ajaxError "canceled". + function cancel() { + if (done()) { + return; + } + + callbackProcessed = true; + deferred.reject(); + if (g) { + $$1.event.trigger("ajaxError", [xhr, s, "canceled"]); + } + endGlobalEvents(); + } + + // Fires the start events and beforeSend; false when the upload must not be posted. + function start() { + g = s.global; + // trigger ajax global events so that activity/block indicators work like normal + if (g && $$1.active++ === 0) { + $$1.event.trigger("ajaxStart"); + } + + if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { + cancel(); + + return false; + } + + if (xhr.aborted) { + // abort() in beforeSend already completed the upload + return false; + } + + if (g) { + $$1.event.trigger("ajaxSend", [xhr, s]); + } + + // an ajaxSend handler may abort too + return !xhr.aborted; + } + + // Resolves the upload; returns {error} when the success callback threw. + function succeed(data) { + var failure; + + try { + s.success.call(s.context, data, "success", xhr); + } catch (err) { + failure = { error: err }; + } + + deferred.resolve(xhr.responseText, "success", xhr); + + if (g) { + $$1.event.trigger("ajaxSuccess", [xhr, s, data]); + } + + return failure; + } + + // Settles the upload with the response reader's {status, data, errMsg}. + function settle(result) { + var status = result.status, + errMsg = result.errMsg; + + if (xhr.aborted) { + // abort() completed the upload while its response was processed + log("upload aborted"); + + return; + } + + // an emulated HTTP error status wins, as in $.ajax; a parse error is kept otherwise + if (xhr.status && !((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)) { + status = "error"; + } + + callbackProcessed = true; + + // ordering of these callbacks/triggers is odd, but that's how $.ajax does it + if (status === "success") { + var failure = succeed(result.data); + + complete(status); + if (failure) { + // the upload is settled; the success callback's exception still reaches the console + throw failure.error; + } + + return; + } + + if (typeof errMsg === "undefined") { + errMsg = xhr.statusText; + } + if (s.error) { + s.error.call(s.context, xhr, status, errMsg); + } + deferred.reject(xhr, "error", errMsg); + if (g) { + $$1.event.trigger("ajaxError", [xhr, s, errMsg]); + } + + complete(status); + } + + return { + xhr: xhr, + deferred: deferred, + start: start, + done: done, + abort: abort, + settle: settle, + // Settles an upload that failed with an exception (ignored once aborted). + fail: function (err) { + settle({ status: "error", errMsg: err }); + }, + // Runs `onTimeout` after s.timeout, when set. + startTimer: function (onTimeout) { + if (s.timeout) { + timeoutHandle = setTimeout(onTimeout, s.timeout); + } + }, + stopTimer: function () { + clearTimeout(timeoutHandle); + timeoutHandle = undefined; + }, + }; +} + +// The iframe transport: posts the form itself into a hidden frame and reads the response from it, +// for file uploads without the File API or when the iframe option asks for it. +var $ = jQuery; + +/** + * The iframe send step. `hasProp` is what the entry detected at load; `forms.property` reads a + * form property as attr2 does. + */ +function createIframeTransport(hasProp, forms) { + var CLIENT_TIMEOUT_ABORT = 1; + var SERVER_ABORT = 2; + // tells apart the frames of uploads that start in the same millisecond + var frameCount = 0; + + // ensure that every serialized input is still enabled + function enableControls(elements) { + for (var i = 0; i < elements.length; i++) { + var el = $(elements[i]); + + if (hasProp) { + el.prop("disabled", false); } else { - io = ownerDocument.createElement("iframe"); - io.setAttribute("name", id); - io.setAttribute("src", s.iframeSrc); - $io = $(io); - $io.css({ position: "absolute", top: "-1000px", left: "-1000px" }); + el.removeAttr("disabled"); } - io = $io[0]; + } + } - xhr = { - // mock object - aborted: 0, - responseText: null, - responseXML: null, - status: 0, - statusText: "n/a", - getAllResponseHeaders: function () {}, - getResponseHeader: function () {}, - setRequestHeader: function () {}, - abort: function (status) { - abortUpload(status, [xhr, "aborted", status]); - }, - }; + // Names the frame's window, when the page may: a cross-origin or sandboxed frame refuses. + function nameWindow(frame, name) { + try { + if (frame.contentWindow) { + frame.contentWindow.name = name; + } + } catch (ignore) {} + } - // Completes an aborted upload once and rejects the Deferred with `rejection`. - function abortUpload(status, rejection) { - var e = status === "timeout" ? "timeout" : "aborted"; + // The frame the form posts into: the iframeTarget, named `id` when it has no name, or a new + // hidden frame named `id`. Returns the frame and the name the form targets. + function createFrame(s, id, ownerDocument) { + var $io, n; - if (xhr.aborted || callbackProcessed) { - return; - } + if (s.iframeTarget) { + $io = $(s.iframeTarget, ownerDocument); + n = $io.attr("name"); + if (!n) { + $io.attr("name", id); + // a frame already in the page keeps the browsing context name it was inserted with + $io.each(function () { + nameWindow(this, id); + }); + } else { + id = n; + } + } else { + var io = ownerDocument.createElement("iframe"); + + io.setAttribute("name", id); + io.setAttribute("src", s.iframeSrc); + $io = $(io); + $io.css({ position: "absolute", top: "-1000px", left: "-1000px" }); + } - log("aborting upload... " + e); - xhr.aborted = 1; + return { $io: $io, id: id }; + } + // The frame hooks the lifecycle calls: stop a load in progress, and release after the upload. + function frameHooks(s, $io) { + return { + stop: function () { try { // #214, #257 - if (io.contentWindow.document.execCommand) { - io.contentWindow.document.execCommand("Stop"); + if ($io[0].contentWindow.document.execCommand) { + $io[0].contentWindow.document.execCommand("Stop"); } } catch (ignore) {} $io.attr("src", s.iframeSrc); // abort op in progress - xhr.error = e; - if (s.error) { - s.error.call(s.context, xhr, e, status); + }, + release: function () { + if (!s.iframeTarget) { + $io.remove(); + } else { + // adding else to clean up existing iframe response. + $io.attr("src", s.iframeSrc); } - deferred.reject.apply(deferred, rejection); + }, + }; + } - if (g) { - $.event.trigger("ajaxError", [xhr, s, e]); - } + function listen(io, cb) { + if (io.attachEvent) { + io.attachEvent("onload", cb); + } else { + io.addEventListener("load", cb, false); + } + } - complete(e); - } + function unlisten(io, cb) { + if (io.detachEvent) { + io.detachEvent("onload", cb); + } else { + io.removeEventListener("load", cb, false); + } + } - // The steps every finished or aborted upload ends with, in $.ajax order. - function complete(status) { - if (g) { - $.event.trigger("ajaxComplete", [xhr, s]); - } + // private function for handling file uploads (hat tip to YAHOO!) + function fileUploadIframe(submission) { + var form = submission.form, + method = submission.method; + + var s = keepContext($.extend(true, {}, $.ajaxSettings, submission.options), [ + $.ajaxSettings, + submission.options, + ]); + + s.context = s.context || s; + var ownerDocument = formMember(form, "ownerDocument"); + var $body = $(closestByTag(form, ["body"])); + var frame = createFrame(s, "jqFormIO" + new Date().getTime() + frameCount++, ownerDocument); + var $io = frame.$io, + io = $io[0]; + var life = createLifecycle(s, frameHooks(s, $io)); + var domCheckCount = 50; + + if (!life.start()) { + return life.deferred; + } + + addSubmitterFields(s, form); + addCsrfField(s, form, method, forms); - if (g && !--$.active) { - $.event.trigger("ajaxStop"); + // look for server aborts + function checkState() { + try { + var state = getDoc(io).readyState; + + log("state = " + state); + if (state && state.toLowerCase() === "uninitialized") { + setTimeout(checkState, 50); } + } catch (e) { + log("Server abort: ", e, " (", e.name, ")"); + cb(SERVER_ABORT); + life.stopTimer(); + } + } + + // take a breath so that pending repaints get some cpu time before the upload starts + function doSubmit() { + var saved = saveAttributes(form); - if (s.complete) { - s.complete.call(s.context, xhr, status); + setUploadAttributes(form, frame.id, method, s, forms); + + // support timout + life.startTimer(function () { + cb(CLIENT_TIMEOUT_ABORT); + }); + + // add "extra" data to form if provided in options + var extraInputs = []; + + try { + addExtraInputs(form, ownerDocument, s.extraData, submission.traditional, extraInputs); + + if (!s.iframeTarget) { + // add iframe to doc and submit the form + $io.appendTo($body); } - if (s.timeout) { - clearTimeout(timeoutHandle); + // A connected form posting into a frame outside the document opens a new window. + var root = ownerDocument.documentElement; + + if (io && $.contains(root, form) && !$.contains(root, io)) { + var notInDocument = "jquery.form: the upload frame is not in the document"; + + life.abort(notInDocument, [life.xhr, "error", notInDocument], "error"); + + return; } - // clean up - setTimeout(function () { - if (!s.iframeTarget) { - $io.remove(); - } else { - // adding else to clean up existing iframe response. - $io.attr("src", s.iframeSrc); - } - xhr.responseXML = null; - }, 100); + listen(io, cb); + setTimeout(checkState, 15); + submitForm(form); + } finally { + // reset attrs and remove "extra" input elements + restoreAttributes(form, saved); + $(extraInputs).remove(); } + } - g = s.global; - // trigger ajax global events so that activity/block indicators work like normal - if (g && $.active++ === 0) { - $.event.trigger("ajaxStart"); - } - if (g) { - $.event.trigger("ajaxSend", [xhr, s]); + // Reads the next document by Opera's rules: false once the retries are used up. + function retry() { + if (--domCheckCount) { + log("requeing onLoad callback, DOM not available"); + setTimeout(cb, 250); + + return true; } - if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { - if (s.global) { - $.active--; - } - deferred.reject(); + return false; + } - return deferred; + function cb(e) { + if (life.done()) { + return; } - if (xhr.aborted) { - // abort() in beforeSend already rejected the Deferred - return deferred; + var doc = getDoc(io); + + if (!doc) { + log("cannot access response document"); + e = SERVER_ABORT; } + if (e === CLIENT_TIMEOUT_ABORT) { + life.abort("timeout", [life.xhr, "timeout"]); - // add submitting element to data if we know it - sub = form.clk; - if (sub) { - n = sub.name; - if (n && !sub.disabled) { - s.extraData = s.extraData || {}; - s.extraData[n] = sub.value; - if (sub.type === "image") { - s.extraData[n + ".x"] = form.clk_x; - s.extraData[n + ".y"] = form.clk_y; - } - } + return; } + if (e === SERVER_ABORT) { + life.abort("server abort", [life.xhr, "error", "server abort"]); - var CLIENT_TIMEOUT_ABORT = 1; - var SERVER_ABORT = 2; + return; + } - function getDoc(frame) { - /* it looks like contentWindow or contentDocument do not - * carry the protocol property in ie8, when running under ssl - * frame.document is the only valid response document, since - * the protocol is know but not on the other two objects. strange? - * "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy - */ + if (doc.location.href === s.iframeSrc) { + // response not received yet + return; + } - var doc = null; + unlisten(io, cb); - // IE8 cascading access check - try { - if (frame.contentWindow) { - doc = frame.contentWindow.document; - } - } catch (err) { - // IE8 access denied under ssl & missing protocol - log("cannot get iframe.contentWindow document: " + err); - } + var result = readResponse(doc, life.xhr, s, retry); - if (doc) { - // successful getting content - return doc; - } + if (result) { + life.settle(result); + } + } - try { - // simply checking may throw in ie8 under ssl or mismatched protocol - doc = frame.contentDocument ? frame.contentDocument : frame.document; - } catch (err) { - // last attempt - log("cannot get iframe.contentDocument: " + err); - doc = frame.document; - } + // An exception while posting settles the upload with "error" and the exception. + function post() { + if (life.done()) { + // aborted before the delayed post + return; + } - return doc; + try { + doSubmit(); + } catch (err) { + log("upload failed: ", err); + life.fail(err); } + } - // Rails CSRF hack (thanks to Yvan Barthelemy); like jquery-ujs, only for the page's origin and - // only when the form is posted, since a get form would put the token in the url - var csrf_token = $("meta[name=csrf-token]").attr("content"); - var csrf_param = $("meta[name=csrf-param]").attr("content"); - var posts = !method || /post/i.test(method) || /post/i.test($form.attr2("method")); + if (s.forceSync) { + post(); + } else { + setTimeout(post, 10); // this lets dom updates render + } - if (csrf_param && csrf_token && posts && isSameOrigin(s.url)) { - s.extraData = s.extraData || {}; - s.extraData[csrf_param] = csrf_token; - } + return life.deferred; + } - function setFormAttribute(name, value) { - plainForm.setAttribute.call(form, name, value); - } + return function sendIframe(submission) { + var jqxhr; - // take a breath so that pending repaints get some cpu time before the upload starts - function doSubmit() { - // make sure form attrs are set - var t = $form.attr2("target"), - a = $form.attr2("action"), - mp = "multipart/form-data", - et = $form.attr("enctype") || $form.attr("encoding") || mp; - - // update form attrs in IE friendly way - setFormAttribute("target", id); - if (!method || /post/i.test(method)) { - setFormAttribute("method", "POST"); - } - if (a !== s.url) { - setFormAttribute("action", s.url); - } + // now, while the controls are still listed: ajaxSubmit clears the list when it returns, + // before a closeKeepAlive request completes + enableControls(submission.controls); - // ie borks in some cases when setting encoding - if (!s.skipEncodingOverride && (!method || /post/i.test(method))) { - setFormAttribute("encoding", mp); - setFormAttribute("enctype", mp); - } + // hack to fix Safari hang (thanks to Tim Molendijk for this) + // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d + if (submission.options.closeKeepAlive) { + deprecate("closeKeepAlive", "closeKeepAlive works around a Safari 3/4 bug and is deprecated"); + $.get(submission.options.closeKeepAlive, function () { + jqxhr = fileUploadIframe(submission); + }); + } else { + jqxhr = fileUploadIframe(submission); + } - // support timout - if (s.timeout) { - timeoutHandle = setTimeout(function () { - cb(CLIENT_TIMEOUT_ABORT); - }, s.timeout); - } + return jqxhr; + }; +} - // look for server aborts - function checkState() { - try { - var state = getDoc(io).readyState; +// A Submission is one ajaxSubmit call once its vetoes have passed: +// { form, $form, fields, controls, options, method, traditional }. `options` is the object the +// callbacks and events receive; later steps change it in place. - log("state = " + state); - if (state && state.toLowerCase() === "uninitialized") { - setTimeout(checkState, 50); - } - } catch (e) { - log("Server abort: ", e, " (", e.name, ")"); - cb(SERVER_ABORT); - if (timeoutHandle) { - clearTimeout(timeoutHandle); - } - timeoutHandle = undefined; - } - } +/** + * The submission steps. `feature` holds what the entry detected at load (fileapi, formdata), and + * `forms` reads form attributes and attr2-style properties (attribute, property), and + * `serialization` collects the form's fields and controls. + */ +function createSubmission(feature, forms, serialization) { + var $ = jQuery; - // add "extra" data to form if provided in options - var extraInputs = []; + function refuse(message) { + log(message); - // Builds the input with DOM properties: a name is never parsed as HTML. - function addHiddenInput(name, value) { - var input = ownerDocument.createElement("input"); + return null; + } - input.type = "hidden"; - input.name = name; - extraInputs.push($(input).val(value).appendTo(form)[0]); - } + // The options merged over the form's action, the method, and the ajax defaults. + function withDefaults(form, options, method) { + var action = options.url || forms.property(form, "action"); + var url = typeof action === "string" ? action.trim() : ""; - try { - if (s.extraData) { - for (var n in s.extraData) { - if (hasOwn.call(s.extraData, n)) { - // if using the $.param format that allows for multiple values with the same name - if ( - $.isPlainObject(s.extraData[n]) && - hasOwn.call(s.extraData[n], "name") && - hasOwn.call(s.extraData[n], "value") - ) { - addHiddenInput(s.extraData[n].name, s.extraData[n].value); - } else { - // arrays and objects become one field per value, as $.param sends them (#597) - var single = {}; - - single[n] = s.extraData[n]; - var fields = deepSerialize(single); - - for (var f = 0; f < fields.length; f++) { - addHiddenInput(fields[f][0], fields[f][1]); - } - } - } - } - } + // clean url (don't include hash value); an action that is only a fragment means this page + url = url.split("#")[0] || window.location.href.split("#")[0]; + // IE requires javascript:false in https, but this breaks chrome >83 and goes against spec. + // Instead of using javascript:false always, let's only apply it for IE. + var isMsie = /(MSIE|Trident)/.test(navigator.userAgent || ""); + var iframeSrc = isMsie && /^https/i.test(document.URL) ? "javascript:false" : "about:blank"; // eslint-disable-line no-script-url - if (!s.iframeTarget) { - // add iframe to doc and submit the form - $io.appendTo($body); - } + var merged = $.extend( + true, + { + url: url, + success: $.ajaxSettings.success, + type: method || $.ajaxSettings.type, + iframeSrc: iframeSrc, + }, + options + ); - if (io.attachEvent) { - io.attachEvent("onload", cb); - } else { - io.addEventListener("load", cb, false); - } + return keepContext(merged, [options]); + } + + /** + * The one method every transport sends, read after the hooks: `method` wins over `type`, and + * `type` is set to it. Undefined when only the ajax default applies, so each transport keeps + * its own default. + */ + function resolveMethod(options, defaultType) { + var resolved = options.method || options.type; - setTimeout(checkState, 15); + options.type = resolved; - try { - form.submit(); - } catch (err) { - // just in case form has element with name/id of 'submit' - plainForm.submit.call(form); - } - } finally { - // reset attrs and remove "extra" input elements - if (typeof a === "string") { - setFormAttribute("action", a); - } else { - // a control named action hid a missing action attribute - plainForm.removeAttribute.call(form, "action"); - } - setFormAttribute("enctype", et); // #380 - if (t) { - setFormAttribute("target", t); - } else { - plainForm.removeAttribute.call(form, "target"); - } - $(extraInputs).remove(); - } + return resolved === defaultType && !options.method ? undefined : resolved; + } + + // The data option, kept as extraData and encoded, or undefined without one. + function extraQuery(fields, options, traditional) { + if (!options.data) { + return undefined; + } + + var optionsData = typeof options.data === "function" ? options.data(fields) : options.data; + + if (typeof optionsData === "string") { + if (options.requestFormat === "json") { + throw new Error( + 'jquery.form: requestFormat "json" needs object data; a string data option is a query string' + ); } - if (s.forceSync) { - doSubmit(); + // a query string: sent as-is when urlencoded, as its own fields otherwise + options.extraData = queryPairs(optionsData); + + return optionsData; + } + + options.extraData = optionsData; + + return $.param(optionsData, traditional); + } + + // Sets a key as an own data property, so a name like __proto__ is an ordinary key. + function defineKey(object, key, value) { + Object.defineProperty(object, key, { + value: value, + enumerable: true, + writable: true, + configurable: true, + }); + } + + /** + * requestFormat "json" (#545): the fields as an object (a repeated name gives an array), merged + * with object data, sent as a JSON body. Based on the idea in PR #557 by zhangciwu. + */ + function jsonBody(options, fields) { + if (/^get$/i.test(options.type)) { + throw new Error('jquery.form: requestFormat "json" needs a method with a body, such as POST'); + } + + var body = {}; + var own = Object.prototype.hasOwnProperty; + + for (var i = 0; i < fields.length; i++) { + var name = fields[i].name; + + if (!own.call(body, name)) { + defineKey(body, name, fields[i].value); + } else if (Array.isArray(body[name])) { + body[name].push(fields[i].value); } else { - setTimeout(doSubmit, 10); // this lets dom updates render + defineKey(body, name, [body[name], fields[i].value]); + } + } + + var extra = options.extraData; + + for (var key in extra) { + if (own.call(extra, key)) { + defineKey(body, key, extra[key]); } + } + + options.data = JSON.stringify(body); + options.contentType = "application/json; charset=UTF-8"; + } + + // The fields of a query string, as the { name, value } list $.param takes. + function queryPairs(query) { + var pairs = []; + var parts = query.split("&"); + + for (var i = 0; i < parts.length; i++) { + if (parts[i]) { + var at = parts[i].indexOf("="); + var name = at < 0 ? parts[i] : parts[i].slice(0, at); + var value = at < 0 ? "" : parts[i].slice(at + 1); + + pairs.push({ name: decodeQuery(name), value: decodeQuery(value) }); + } + } + + return pairs; + } + + function decodeQuery(text) { + return decodeURIComponent(text.replace(/\+/g, " ")); + } + + // Puts the encoded fields in the url for a get, and in the data otherwise. + function encode(options, q, qx) { + if (qx) { + q = q ? q + "&" + qx : qx; + } + + if (options.type.toUpperCase() === "GET") { + // the query goes before any fragment in the url option + var hashAt = options.url.indexOf("#"); + var base = hashAt < 0 ? options.url : options.url.slice(0, hashAt); + + options.url = + base + (base.indexOf("?") >= 0 ? "&" : "?") + q + options.url.slice(base.length); + options.data = null; // data is null for 'get' + } else { + options.data = q; // data is the query string for 'post' + } + } + + // A callback option as a list: an array as given, one function, or none. + function callbackList(callback) { + if (Array.isArray(callback)) { + return callback; + } + + return callback ? [callback] : []; + } + + // Calls each callback in order with the same this and arguments. + function callEach(callbacks, context, args) { + for (var i = 0; i < callbacks.length; i++) { + callbacks[i].apply(context, args); + } + } + + /** + * Resolves the options, serializes the form, and runs the vetoes: the Submission, or null when + * an event or callback stopped it. + */ + function prepare($set, options) { + $set.each(function () { + assertRealParent(this); + }); + + var form = $set[0]; + var method = options.method || options.type || forms.property(form, "method"); + + options = withDefaults(form, options, method); + + // the ajax default type, when neither the caller nor the form gave a method + var defaultType = method ? undefined : options.type; + + // hook for manipulating the form data before it is extracted; + // convenient for use with rich editors like tinyMCE or FCKEditor + var veto = {}; + + $set.trigger("form-pre-serialize", [$set, options, veto]); + if (veto.veto) { + return refuse("ajaxSubmit: submit vetoed via form-pre-serialize trigger"); + } + + // provide opportunity to alter form data before it is serialized + if (options.beforeSerialize && options.beforeSerialize($set, options) === false) { + return refuse("ajaxSubmit: submit aborted via beforeSerialize callback"); + } + + var traditional = options.traditional; + + if (typeof traditional === "undefined") { + traditional = $.ajaxSettings.traditional; + } + + var collected = serialization.collect($set[0], options.semantic, options.filtering); + var fields = collected.fields; + var controls = collected.controls; + var qx = extraQuery(fields, options, traditional); + + // give pre-submit callback an opportunity to abort the submit + if (options.beforeSubmit && options.beforeSubmit(fields, $set, options) === false) { + return refuse("ajaxSubmit: submit aborted via beforeSubmit callback"); + } + + // fire vetoable 'validate' event + $set.trigger("form-submit-validate", [fields, $set, options, veto]); + if (veto.veto) { + return refuse("ajaxSubmit: submit vetoed via form-submit-validate trigger"); + } + + method = resolveMethod(options, defaultType); + + if (options.requestFormat === "json") { + jsonBody(options, fields); + } else { + encode(options, $.param(urlencodedFields(fields), traditional), qx); + } + + return { + form: form, + $form: $set, + fields: fields, + controls: controls, + options: options, + method: method, + traditional: traditional, + }; + } + + /** + * Wraps success, error and complete (a function or an array of them, as $.ajax takes) so each + * also receives the form, and adds the resetForm, + * clearForm and target steps before the success callbacks. + */ + function deliver(submission) { + var $set = submission.$form; + var options = submission.options; + var callbacks = []; + + if (options.resetForm) { + callbacks.push(function () { + $set.resetForm(); + }); + } + + if (options.clearForm) { + callbacks.push(function () { + $set.clearForm(options.includeHidden); + }); + } - var data, - doc, - domCheckCount = 50; + // perform a load on the target only if dataType is not provided + if (!options.dataType && options.target) { + var successes = callbackList(options.success); - function cb(e) { - if (xhr.aborted || callbackProcessed) { - return; - } + callbacks.push(function (data, textStatus, jqXHR) { + var successArguments = arguments, + fn = options.replaceTarget ? "replaceWith" : "html", + $target = $(options.target); - doc = getDoc(io); - if (!doc) { - log("cannot access response document"); - e = SERVER_ABORT; + // Only a string response is inserted. jQuery has already parsed a JSON or XML response, + // and inserting it would parse each of its strings as HTML. + if (typeof data === "string") { + $target[fn](data); + } else { + log("target: the response was parsed by jQuery, so it is not inserted"); } - if (e === CLIENT_TIMEOUT_ABORT && xhr) { - abortUpload("timeout", [xhr, "timeout"]); - return; + if (!$target.length) { + // nothing to fill: success still runs once, with the normal context + callEach(successes, this, successArguments); } - if (e === SERVER_ABORT && xhr) { - abortUpload("server abort", [xhr, "error", "server abort"]); - return; - } + $target.each(function () { + callEach(successes, this, successArguments); + }); + }); + } else { + $.merge(callbacks, callbackList(options.success)); + } - if (doc.location.href === s.iframeSrc) { - // response not received yet - return; - } + options.success = function (data, status, xhr) { + // jQuery 1.4+ passes xhr as 3rd arg + var context = options.context || this; // jQuery 1.4+ supports scope context - if (io.detachEvent) { - io.detachEvent("onload", cb); - } else { - io.removeEventListener("load", cb, false); - } + for (var i = 0, max = callbacks.length; i < max; i++) { + callbacks[i].apply(context, [data, status, xhr || $set, $set]); + } + }; - var status = "success", - errMsg; + if (options.error) { + var errors = callbackList(options.error); - try { - var isXml = s.dataType === "xml" || doc.XMLDocument || $.isXMLDoc(doc); + options.error = function (xhr, status, error) { + callEach(errors, options.context || this, [xhr, status, error, $set]); + }; + } - log("isXml=" + isXml); + if (options.complete) { + var completes = callbackList(options.complete); - if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) { - if (--domCheckCount) { - // in some browsers (Opera) the iframe DOM is not always traversable when - // the onload callback fires, so we loop a bit to accommodate - log("requeing onLoad callback, DOM not available"); - setTimeout(cb, 250); + options.complete = function (xhr, status) { + callEach(completes, options.context || this, [xhr, status, $set]); + }; + } + } - return; - } - // let this fall through because server response could be an empty document - // log('Could not access iframe DOM after mutiple tries.'); - // throw 'DOMException: not available'; - } + /** + * The transport for a submission: "iframe" for files without the File API or when forced, + * "formdata" for files with it, "ajax" otherwise. + */ + function chooseTransport(submission) { + var $set = submission.$form; + var options = submission.options; - // log('response detected'); - var docRoot = doc.body ? doc.body : doc.documentElement; + // [value] (issue #113), also see comment: + // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219 + // and the file inputs outside the form that belong to it through their form attribute + var fileInputs = $("input[type=file]:enabled", $set) + .add($(submission.controls).filter("input[type=file]")) + .filter(function () { + return $(this).val() !== ""; + }); + var hasFileInputs = fileInputs.length > 0; + // compared as the browser does: ASCII case-insensitive, without surrounding whitespace + var mp = /^[\t\n\f\r ]*multipart\/form-data[\t\n\f\r ]*$/i; + var multipart = + mp.test(forms.attribute($set[0], "enctype")) || mp.test(forms.attribute($set[0], "encoding")); + var fileAPI = feature.fileapi && feature.formdata; - xhr.responseText = docRoot ? docRoot.innerHTML : null; - xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; - if (isXml) { - s.dataType = "xml"; - } - xhr.getResponseHeader = function (header) { - var headers = { "content-type": s.dataType }; - - return headers[header.toLowerCase()]; - }; - // support for XHR 'status' & 'statusText' emulation : - if (docRoot) { - xhr.status = Number(docRoot.getAttribute("status")) || xhr.status; - xhr.statusText = docRoot.getAttribute("statusText") || xhr.statusText; - } + log("fileAPI :" + fileAPI); - var dt = (s.dataType || "").toLowerCase(); - var scr = /(json|script|text)/.test(dt); - - if (scr || s.textarea) { - // see if user embedded response in textarea - var ta = doc.getElementsByTagName("textarea")[0]; - - if (ta) { - xhr.responseText = ta.value; - // support for XHR 'status' & 'statusText' emulation : - xhr.status = Number(ta.getAttribute("status")) || xhr.status; - xhr.statusText = ta.getAttribute("statusText") || xhr.statusText; - } else if (scr) { - // account for browsers injecting pre around json response - var pre = doc.getElementsByTagName("pre")[0]; - var b = doc.getElementsByTagName("body")[0]; - - if (pre) { - xhr.responseText = pre.textContent ? pre.textContent : pre.innerText; - } else if (b) { - xhr.responseText = b.textContent ? b.textContent : b.innerText; - } - } - } + var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI; - try { - data = httpData(xhr, dt, s); // eslint-disable-line no-use-before-define - } catch (err) { - status = "parsererror"; - xhr.error = errMsg = err || status; - } - } catch (err) { - log("error caught: ", err); - status = "error"; - xhr.error = errMsg = err; - } + var transport = (hasFileInputs || multipart) && fileAPI ? "formdata" : "ajax"; - if (xhr.aborted) { - // abort() completed the upload while its response was processed - log("upload aborted"); + // options.iframe allows user to force iframe mode + // 06-NOV-09: now defaulting to iframe mode if file input is detected + if (options.iframe !== false && (options.iframe || shouldUseFrame)) { + transport = "iframe"; + } - return; - } + if (transport === "iframe" && !options.iframe) { + deprecate( + "iframe", + "choosing the iframe transport automatically without FormData is deprecated, set iframe: true" + ); + } - // an emulated HTTP error status wins, as in $.ajax; a parse error is kept otherwise - if (xhr.status && !((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)) { - status = "error"; - } + if (transport !== "ajax" && options.requestFormat === "json") { + throw new Error( + 'jquery.form: requestFormat "json" cannot send files or use the iframe transport' + ); + } - callbackProcessed = true; + return transport; + } - // ordering of these callbacks/triggers is odd, but that's how $.ajax does it - if (status === "success") { - s.success.call(s.context, data, "success", xhr); + return { prepare: prepare, deliver: deliver, chooseTransport: chooseTransport }; +} - deferred.resolve(xhr.responseText, "success", xhr); +(function ($) { - if (g) { - $.event.trigger("ajaxSuccess", [xhr, s]); - } - } else { - if (typeof errMsg === "undefined") { - errMsg = xhr.statusText; - } - if (s.error) { - s.error.call(s.context, xhr, status, errMsg); - } - deferred.reject(xhr, "error", errMsg); - if (g) { - $.event.trigger("ajaxError", [xhr, s, errMsg]); - } - } + /* + Usage Note: + ----------- + Do not use both ajaxSubmit and ajaxForm on the same form. These + functions are mutually exclusive. Use ajaxSubmit if you want + to bind your own submit handler to the form. For example, - complete(status); - } + $(document).ready(function() { + $('#myForm').on('submit', function(e) { + e.preventDefault(); // <-- important + $(this).ajaxSubmit({ + target: '#output' + }); + }); + }); - var httpData = function (xhr, type, s) { - // mostly lifted from jq1.4.4 + Use ajaxForm when you want the plugin to manage all the event binding + for you. For example, - var ct = xhr.getResponseHeader("content-type") || "", - xml = (type === "xml" || !type) && ct.indexOf("xml") >= 0, - data = xml ? xhr.responseXML : xhr.responseText; + $(document).ready(function() { + $('#myForm').ajaxForm({ + target: '#output' + }); + }); - if (xml && data.documentElement.nodeName === "parsererror") { - if ($.error) { - $.error("parsererror"); - } - } - if (s && s.dataFilter) { - data = s.dataFilter(data, type); - } - if (typeof data === "string") { - if ((type === "json" || !type) && ct.indexOf("json") >= 0) { - data = JSON.parse(data); - } else if (type === "script") { - $.globalEval(data); - } - } + You can also use ajaxForm with delegation (requires jQuery v1.7+), so the + form does not have to exist when you invoke ajaxForm: - return data; - }; + $('#myForm').ajaxForm({ + delegation: true, + target: '#output' + }); - return deferred; - } - }; + When using ajaxForm, the ajaxSubmit function will be invoked for you + at the appropriate time. + */ /** - * ajaxForm() provides a mechanism for fully automating form submission. - * - * The advantages of using this method instead of ajaxSubmit() are: - * - * 1: This method will include coordinates for elements (if the element - * is used to submit the form). - * 2. This method will include the submit element's name/value data (for the element that was - * used to submit the form). - * 3. This method binds the submit() method to the form for you. - * - * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely - * passes the options argument along after properly binding events for submit elements and - * the form itself. + * Feature detection */ - $.fn.ajaxForm = function (options, data, dataType, onSuccess) { - if (typeof options === "string" || (options === false && arguments.length > 0)) { - options = { - url: options, - data: data, - dataType: dataType, - }; - - if (typeof onSuccess === "function") { - options.success = onSuccess; - } - } + var feature = {}; - options = options || {}; - options.delegation = options.delegation && typeof $.fn.on === "function"; + feature.fileapi = $('').get(0).files !== undefined; + feature.formdata = typeof window.FormData !== "undefined"; - // in jQuery 1.3+ we can fix mistakes with the ready state - if (!options.delegation && this.length === 0) { - var o = { s: this.selector, c: this.context }; + var hasProp = !!$.fn.prop; + // What attr2 returns for a form: the property when it is a string, otherwise the attribute. The + // property is read plainly on purpose: a control named like it shadows it, and then the raw + // attribute is used. + function formProperty(form, name) { + var value = hasProp ? form[name] : undefined; - if (!$.isReady && o.s) { - log("DOM not ready, queuing ajaxForm"); - $(function () { - $(o.s, o.c).ajaxForm(options); - }); + return typeof value === "string" ? value : formAttribute(form, name); + } - return this; - } + var forms = { attribute: formAttribute, property: formProperty }; + var serialization = createSuccessfulControls(feature); + var steps = createSubmission(feature, forms, serialization); + var transports = { + iframe: createIframeTransport(hasProp, forms), + formdata: sendFormData, + ajax: sendAjax, + }; - // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() - log("terminating; zero elements found by selector" + ($.isReady ? "" : " (DOM not ready)")); + // attr2 uses prop when it can but checks the return type for + // an expected string. This accounts for the case where a form + // contains inputs with names like "action" or "method"; in those + // cases "prop" returns the element + $.fn.attr2 = function () { + deprecate("attr2", "attr2 is deprecated, use .prop() or .attr()"); - return this; + if (!hasProp) { + return this.attr.apply(this, arguments); } - if (options.delegation) { - $(document) - .off("submit.form-plugin", this.selector, doAjaxSubmit) - .off("click.form-plugin", this.selector, captureSubmittingElement) - .on("submit.form-plugin", this.selector, options, doAjaxSubmit) - .on("click.form-plugin", this.selector, options, captureSubmittingElement); - - return this; - } + var val = this.prop.apply(this, arguments); - if (options.beforeFormUnbind) { - options.beforeFormUnbind(this, options); + if ((val && val.jquery) || typeof val === "string") { + return val; } - return this.ajaxFormUnbind() - .on("submit.form-plugin", options, doAjaxSubmit) - .on("click.form-plugin", options, captureSubmittingElement); + return this.attr.apply(this, arguments); }; - // private event handlers - function doAjaxSubmit(e) { - /* jshint validthis:true */ - var options = e.data; + /** + * ajaxSubmit() provides a mechanism for immediately submitting + * an HTML form using AJAX. + * + * @param {object|string} options jquery.form.js parameters or custom url for submission + * @param {object} data extraData + * @param {string} dataType ajax dataType + * @param {function} onSuccess ajax success callback function + */ + $.fn.ajaxSubmit = function (options, data, dataType, onSuccess) { + deprecateOldJQuery($.fn.jquery); - if (!e.isDefaultPrevented()) { - // if event has been canceled, don't proceed - e.preventDefault(); - $(e.target).closest("form").ajaxSubmit(options); // #365 - } - } + // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) + if (!this.length) { + log("ajaxSubmit: skipping submit process - no element selected"); - function captureSubmittingElement(e) { - /* jshint validthis:true */ - // the clicked control, or the button around the clicked content (ex: a span within a button) - var $el = $(e.target).closest("button,input"); - var target = $el[0]; + return this; + } - // the type property, unlike the attribute, is "submit" for a button without a type (#588) - if (!target || (target.type !== "submit" && target.type !== "image")) { - return; + // #541: jQuery's slim build has no $.ajax + if (!$.ajax) { + throw new Error( + "jquery.form: ajaxSubmit needs the full jQuery build; this jQuery has no $.ajax" + ); } - var form = target.form; + var submission = steps.prepare(this, submitOptions(options, data, dataType, onSuccess)); - if (!form) { - // a submit control that belongs to no form - return; + if (!submission) { + return this; } - form.clk = target; + steps.deliver(submission); - if (target.type === "image") { - if (typeof e.offsetX !== "undefined") { - form.clk_x = e.offsetX; - form.clk_y = e.offsetY; - } else if (typeof $.fn.offset === "function") { - var offset = $el.offset(); + var jqxhr = transports[steps.chooseTransport(submission)](submission); - form.clk_x = e.pageX - offset.left; - form.clk_y = e.pageY - offset.top; - } else { - form.clk_x = e.pageX - target.offsetLeft; - form.clk_y = e.pageY - target.offsetTop; - } + this.removeData("jqxhr").data("jqxhr", jqxhr); + + // clear element array + for (var k = 0; k < submission.controls.length; k++) { + submission.controls[k] = null; } - // clear form vars - setTimeout(function () { - form.clk = form.clk_x = form.clk_y = null; - }, 100); - } - // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm - $.fn.ajaxFormUnbind = function () { - return this.off("submit.form-plugin click.form-plugin"); + // fire 'notify' event + this.trigger("form-submit-notify", [this, submission.options]); + + return this; }; + $.fn.ajaxForm = ajaxForm; + $.fn.ajaxFormUnbind = ajaxFormUnbind; + /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. @@ -1145,109 +2325,13 @@ export { default } from 'jquery'; * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function (semantic, elements, filtering) { - var a = []; - - if (this.length === 0) { - return a; - } - - var form = this[0]; - var formId = this.attr("id"); - var els = - semantic || typeof form.elements === "undefined" - ? form.getElementsByTagName("*") - : formElements(form); - var els2; - - if (els) { - els = $.makeArray(els); // convert to standard array - } - - // #386; account for inputs outside the form which use the 'form' attribute - // FinesseRus: in non-IE browsers outside fields are already included in form.elements. - if (formId && (semantic || /(Edge|Trident)\//.test(navigator.userAgent))) { - // hat tip @thet; the id is compared, never built into a selector - els2 = $(":input[form]") - .filter(function () { - return this.getAttribute("form") === formId; - }) - .get(); - if (els2.length) { - els = els.concat(els2); - } - } - - if (!els || !els.length) { - return a; - } + var collected = serialization.collect(this[0], semantic, filtering); - if (typeof filtering === "function") { - els = $.map(els, filtering); - } - - var i, j, n, v, el, max, jmax; - - for (i = 0, max = els.length; i < max; i++) { - el = els[i]; - n = el.name; - if (!n || el.disabled) { - continue; - } - - if (semantic && form.clk && el.type === "image") { - // handle image inputs on the fly when semantic == true - if (form.clk === el) { - a.push({ name: n, value: $(el).val(), type: el.type }); - a.push({ name: n + ".x", value: form.clk_x }, { name: n + ".y", value: form.clk_y }); - } - continue; - } - - v = $.fieldValue(el, true); - if (v && v.constructor === Array) { - if (elements) { - elements.push(el); - } - for (j = 0, jmax = v.length; j < jmax; j++) { - a.push({ name: n, value: v[j] }); - } - } else if (feature.fileapi && el.type === "file") { - if (elements) { - elements.push(el); - } - - var files = el.files; - - if (files.length) { - for (j = 0; j < files.length; j++) { - a.push({ name: n, value: files[j], type: el.type }); - } - } else { - // #180 - a.push({ name: n, value: "", type: el.type }); - } - } else if (v !== null && typeof v !== "undefined") { - if (elements) { - elements.push(el); - } - a.push({ name: n, value: v, type: el.type, required: el.required }); - } + if (elements) { + elements.push.apply(elements, collected.controls); } - if (!semantic && form.clk) { - // input type=='image' are not found in elements array! handle it here - var $input = $(form.clk), - input = $input[0]; - - n = input.name; - - if (n && !input.disabled && input.type === "image") { - a.push({ name: n, value: $input.val() }); - a.push({ name: n + ".x", value: form.clk_x }, { name: n + ".y", value: form.clk_y }); - } - } - - return a; + return collected.fields; }; /** @@ -1256,7 +2340,7 @@ export { default } from 'jquery'; */ $.fn.formSerialize = function (semantic) { // hand off to jQuery.param for proper encoding - return $.param(this.formToArray(semantic)); + return $.param(urlencodedFields(this.formToArray(semantic))); }; /** @@ -1269,7 +2353,8 @@ export { default } from 'jquery'; this.each(function () { var n = this.name; - if (!n) { + // a form is not a field, though it may have a name + if (!n || tagName(this) === "form") { return; } @@ -1349,65 +2434,13 @@ export { default } from 'jquery'; * Returns the value of the field element. */ $.fieldValue = function (el, successful) { - var n = el.name, - t = el.type, - tag = tagName(el); - - if (typeof successful === "undefined") { - successful = true; - } - - if ( - successful && - (!n || - el.disabled || - t === "reset" || - t === "button" || - ((t === "checkbox" || t === "radio") && !el.checked) || - ((t === "submit" || t === "image") && el.form && el.form.clk !== el) || - (tag === "select" && el.selectedIndex === -1)) - ) { - return null; - } + var required = typeof successful === "undefined" || successful; - if (tag === "select") { - var index = el.selectedIndex; - - if (index < 0) { - return null; - } - - var a = [], - ops = el.options; - var one = t === "select-one"; - var max = one ? index + 1 : ops.length; - - for (var i = one ? index : 0; i < max; i++) { - var op = ops[i]; - - if (op.selected && !op.disabled) { - var v = op.value; - - if (!v) { - // extra pain for IE... - v = - op.attributes && op.attributes.value && !op.attributes.value.specified - ? op.text - : op.value; - } - - if (one) { - return v; - } - - a.push(v); - } - } - - return a; + if (required && !isSuccessful(el, submitterElement(el.form))) { + return null; } - return $(el).val().replace(rCRLF, "\r\n"); + return valueOf(el); }; /** @@ -1427,9 +2460,15 @@ export { default } from 'jquery'; /** * Clears the selected form elements. */ - $.fn.clearFields = $.fn.clearInputs = function (includeHidden) { + $.fn.clearInputs = function (includeHidden) { + deprecate("clearInputs", "clearInputs is deprecated, use clearFields"); + + return this.clearFields(includeHidden); + }; + + $.fn.clearFields = function (includeHidden) { var re = - /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list + /^(?:color|date|datetime|datetime-local|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list return this.each(function () { var t = this.type, @@ -1480,7 +2519,16 @@ export { default } from 'jquery'; switch (tag) { case "input": this.checked = this.defaultChecked; - // fall through + + // as the native reset: types whose value is the value attribute keep it + if (this.type === "file") { + // a file input cannot take its value attribute; the native reset empties it + this.value = ""; + } else if (!/^(?:checkbox|radio|hidden|submit|reset|button|image)$/.test(this.type)) { + this.value = this.defaultValue; + } + + return true; case "textarea": this.value = this.defaultValue; @@ -1504,14 +2552,9 @@ export { default } from 'jquery'; return true; case "select": - // eslint-disable-next-line consistent-return -- jQuery .each() break semantics - el.find("option").each(function (i) { + // in order, as the native reset: of several default options, a single select keeps the last + el.find("option").each(function () { this.selected = this.defaultSelected; - if (this.defaultSelected && !el[0].multiple) { - el[0].selectedIndex = i; - - return false; - } }); return true; @@ -1526,14 +2569,8 @@ export { default } from 'jquery'; return true; case "form": - // guard against an input with the name of 'reset' - // note that IE reports the reset function as an 'object' - if ( - typeof this.reset === "function" || - (typeof this.reset === "object" && !this.reset.nodeType) - ) { - this.reset(); - } + // through the prototype: a control named reset shadows the method + callFormMethod(this, "reset"); return true; @@ -1587,19 +2624,4 @@ export { default } from 'jquery'; // expose debug var $.fn.ajaxSubmit.debug = false; - - // helper fn for console logging - function log() { - if (!$.fn.ajaxSubmit.debug) { - return; - } - - var msg = "[jquery.form] " + Array.prototype.join.call(arguments, ""); - - if (window.console && window.console.log) { - window.console.log(msg); - } else if (window.opera && window.opera.postError) { - window.opera.postError(msg); - } - } })(jQuery); diff --git a/docs/api.md b/docs/api.md index 94e9685..6dc9011 100644 --- a/docs/api.md +++ b/docs/api.md @@ -18,6 +18,16 @@ $(function () { }); ``` +### ajaxFormUnbind + +Removes the handlers `ajaxForm` bound on the selection, and every delegated binding (the `delegation` option) the plugin made on the document. `ajaxFormUnbind(selector)` removes only the delegated binding for that selector and leaves the selection's handlers. Calling `ajaxForm` again on a form does not remove delegated bindings. +Chainable: Yes. + +```javascript +$("#myFormId").ajaxFormUnbind(); +$(document).ajaxFormUnbind("form.ajax"); +``` + ### ajaxSubmit Immediately submits the form via AJAX. In the most common use case this is invoked in response to the user clicking a submit button on the form. `ajaxSubmit` takes zero or one argument. The single argument can be either a callback function or an [Options Object](http://malsup.com/jquery/form/#options-object). diff --git a/docs/metrics.md b/docs/metrics.md index 683d04e..8368abb 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -4,40 +4,40 @@ Before-and-after numbers for the v4 and v5 release announcements. Add a column w Machine: Apple Silicon Mac, Node v24.11.0 (baseline), Node v26.12.1 (Phase 3 onward). -| Metric | v4.3.0 baseline (2026-10-25) | Phase 3 toolchain (2026-10-25) | Phase 3B CI baseline (2026-10-25) | Playwright cache (2026-10-25) | Phase 4B test rewrite (2026-10-25) | Phase 5 coverage (2026-10-25) | Phase 6 deps (2026-10-25) | Phase 7 triage (2026-10-29) | Phase 8 review (2026-10-31) | Phase 9 coverage (2026-10-31) | Phase 10 public fixes (2026-10-31) | 4.4.0 release (2026-11-07) | -| ------------------------------------------------------- | --------------------------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------ | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | -| Test runner | Mocha 7 in PhantomJS via Grunt | Vitest 5 browser mode (Chromium via Playwright) | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | -| Tests | 59 (async tests do not await their assertions) | 64: the same 59, unmodified, plus 5 publish-surface smoke tests | Unchanged | Unchanged | 64: the same 59 rewritten as BDD/AAA with async assertions awaited, plus 5 surface tests | 194: 189 suite (6 are `it.fails` bug records) plus 5 surface tests | 199: 188 suite (6 are `it.fails`), 5 publish-surface, 6 manifest | 204: 192 suite (10 are `it.fails`, 4 new for open issues), 5 publish-surface, 7 manifest and dist (1 `it.fails`) | Unchanged | 206: 194 suite (9 are `it.fails`; the script response record is now an `it`, plus 2 new tests), 5 publish-surface, 7 manifest and dist (1 `it.fails`) | 229: 217 suite (3 are `it.fails`; 6 records are now `it`, plus 23 new tests), 5 publish-surface, 7 manifest and dist (the #553 record is now an `it`) | 245: 233 suite (1 `it.fails`, delegation; the label and #597 records are now `it`, plus 16 new tests), 5 publish-surface, 7 manifest and dist | -| Suite time | 0.81 s in-browser, 7.0 s wall (`npx grunt mocha`) | 0.53 s in-runner, 0.9 s wall (`npx vitest run`) | Unchanged | Unchanged | 1.15 s in-runner (all projects), includes about 0.6 s of deliberate waits | 3.35 s in-runner (all projects), includes deliberate waits and iframe round trips | 3.35 s in-runner (all projects), 3.8 s wall (`npx vitest run`) | Unchanged | Unchanged | 3.45 s in-runner (all projects), 3.9 s wall (`npx vitest run`) | 3.23 s in-runner (all projects), 3.6 s wall (`npx vitest run`) | 4.69 s wall (`npx vitest run`) | -| Full `npm test` | Not defined | 1.5 s wall (lint, build, tests, coverage) | Unchanged | Unchanged | 2.6 s wall | 4.75 s wall | 6.6 s wall | 6.9 s wall | Unchanged | 5.0 s wall | 4.7 s wall | 8.1 s wall | -| Line coverage of `src` | Not measured by the toolchain (about 60% under the prototype runners) | 35.4% | Unchanged | Unchanged | 35.95% | 98.14% | 98.13% | Unchanged | Unchanged | 100% | Unchanged | Unchanged | -| Branch coverage of `src` | Not measured (about 53% under the prototype runners) | 33.9% | Unchanged | Unchanged | Unchanged | 96.41% | 96.40% | Unchanged | Unchanged | 100% | Unchanged | Unchanged | -| Function coverage of `src` | Not measured | Not recorded | Unchanged | Unchanged | 43.10% | 98.27% | 98.24% | Unchanged | Unchanged | 100% | Unchanged | Unchanged | -| Statement coverage of `src` | Not measured | Not recorded | Unchanged | Unchanged | 36.77% | 98.17% | 98.16% | Unchanged | Unchanged | 100% | Unchanged | Unchanged | -| Coverage enforced | No | No (reported on every run) | Unchanged | Unchanged | Unchanged | Yes: lines 98.14%, branches 96.41%, functions 98.27%, statements 98.17% | Yes: lines 98.13%, branches 96.4%, functions 98.24%, statements 98.16% (same uncovered code; the `eval` fallback is gone) | Unchanged | Unchanged | Yes: 100% on all four | Unchanged | Unchanged | -| `dist/jquery.form.min.js` | 17.09 kB min, 6.57 kB gzip | 17.18 kB min, 6.57 kB gzip | Unchanged | Unchanged | Unchanged | Unchanged | 17.15 kB min, 6.55 kB gzip | Unchanged | Unchanged | 16.70 kB min, 6.38 kB gzip | 17.10 kB min, 6.57 kB gzip | 17.45 kB min, 6.67 kB gzip | -| `npm audit` | 51 (11 critical, 25 high, 10 moderate, 5 low) | 0 | Unchanged | Unchanged | Unchanged | Unchanged | 0 vulnerabilities | Unchanged | Unchanged | Unchanged | 6 moderate, dev only (`minimatch` via ESLint, GHSA-g3hv-75wg-m249); 0 with `--omit=dev` | 0 (`minimatch` override, PR #638) | -| Dev dependencies (direct) | 8 | 15 | Unchanged | Unchanged | Unchanged | Unchanged | 15 (no upgrades were available; see `docs/research/jquery-matrix.md`) | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | -| jQuery versions tested | 3.5.1 only (from the CDN) | 3.7.1 (suite and surfaces), 4.0.0 (ESM surface only) | Unchanged | Unchanged | Unchanged | Unchanged | 1.7.2, 3.7.1 and 4.0.0, all gating in CI; the ESM surface test also loads 4.0.0 | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | -| CI | Travis and CircleCI configs (inactive) | GitHub Actions (duration recorded after the first run on `main`) | 6 warm runs, median (min–max); 1 cold run. Steps below | 6 warm runs, 1 cold run; steps below | Unchanged | 1 warm run; steps below | Run 40992583331 (warm); the `jquery` matrix jobs run in parallel with `test` | Run 40999832492 (PR, warm) | Run 41227104628 (PR, warm) | Run 41258062402 (PR, warm) | Run 41263541622 (PR, warm) | Run 42332118377 (release PR, warm) | -| Open issues / PRs | 27 / 8 | 27 / 8 | 27 / 8 | 27 / 8 | Unchanged | 27 / 9 (includes PR #626) | 27 / 9 (includes PR #627) | 12 / 3 (15 issues and 5 PRs closed; closures posted 2026-10-30) | 13 / 1 (#629 opened; PRs #586 and #611 closed) | Unchanged | Unchanged | Unchanged until the release closures | -| CI queue time | — | — | 3 s (2–3 s) | 3 s (2–3 s) | Unchanged | 3 s | 2 s | 3 s | 3 s | 3 s | 3 s | 2 s | -| CI total wall time | — | — | 31 s (27–33 s); cold 32 s | 27 s (22–31 s); cold 36 s | Unchanged | 35 s | 31 s (`test` job) | 29 s (`test` job) | 26 s (`test` job) | 27 s (`test` job) | 32 s (`test` job) | 30 s (`test` job) | -| CI step: setup-node (npm cache) | — | — | 6.5 s (5–8 s); cold 5 s | 6.5 s (6–7 s); cold 6 s | Unchanged | 7 s | 6 s | 5 s | 5 s | 6 s | 5 s | 5 s | -| CI step: `npm ci` | — | — | 1 s (1–2 s); cold 2 s | 1 s (0–2 s); cold 2 s | Unchanged | 2 s | 2 s | 2 s | 1 s | 1 s | 2 s | 2 s | -| CI step: Playwright Chromium install | — | — | 8 s (7–10 s); cold 10 s | 1 s (0–1 s) plus 3 s cache restore; cold 10 s plus 4 s cache save | Unchanged | 1 s plus 4 s cache restore | 1 s (cache 3 s) | 1 s (cache 3 s) | 1 s (cache 2 s) | 1 s (cache 3 s) | 0 s (cache 3 s) | 1 s (cache 3 s) | -| CI step: lint | — | — | 1 s (0–1 s) | 0 s (0–1 s) | Unchanged | 1 s | 1 s | 1 s | 1 s | 0 s | 1 s | 1 s | -| CI step: format check | — | — | 1 s (0–1 s) | 1 s (1–2 s) | Unchanged | 1 s | 1 s | 2 s | 1 s | 1 s | 2 s | 1 s | -| CI step: build | — | — | 0.5 s (0–1 s) | 1 s (0–1 s) | Unchanged | 1 s | 1 s | 0 s | 1 s | 1 s | 1 s | 1 s | -| CI step: Vitest with coverage | — | — | 3 s (3–4 s) | 2.5 s (1–4 s) | Unchanged | 6 s | 6 s | 7 s | 6 s | 5 s | 8 s | 8 s | -| CI step: checkout, job setup, dist check, report upload | — | — | about 1 s each | about 1 s each | Unchanged | 0–2 s each | 0–1 s each | 0–1 s each | 0–1 s each | 0–1 s each | 0–2 s each | 0–1 s each | -| Source lines: physical / code / comment-only | 1592 / 1050 / 289 | — | — | — | — | — | — | — | 1562 / 1029 / 279 | 1529 / 999 / 278 | 1584 / 1029 / 292 | 1607 / 1040 / 300 | -| Functions | 60 | — | — | — | — | — | — | — | 57 | 56 | 62 | 64 | -| Cyclomatic complexity: total / mean / max | 417 / 6.95 / 62 | — | — | — | — | — | — | — | 407 / 7.14 / 62 | 386 / 6.89 / 54 | 400 / 6.45 / 52 | 407 / 6.36 / 52 | -| Functions with complexity > 10 | 10 | — | — | — | — | — | — | — | 10 | 10 | Unchanged | 10 | -| Max block nesting depth | 5 | — | — | — | — | — | — | — | 5 | 5 | Unchanged | 6 | -| Public API: `$.fn` / `$` members | 14 / 1 | — | — | — | — | — | — | — | 14 / 1 | Unchanged | Unchanged | Unchanged | -| CodeQL alerts (open) | — | — | — | — | — | — | — | — | 3 in `src/` on `main` (alerts 1, 4 and 7) | Unchanged | Unchanged (the PR adds none) | 1 expected (alert 7, `iframeTarget`); alerts 1 and 4 close | +| Metric | v4.3.0 baseline (2026-10-25) | Phase 3 toolchain (2026-10-25) | Phase 3B CI baseline (2026-10-25) | Playwright cache (2026-10-25) | Phase 4B test rewrite (2026-10-25) | Phase 5 coverage (2026-10-25) | Phase 6 deps (2026-10-25) | Phase 7 triage (2026-10-29) | Phase 8 review (2026-10-31) | Phase 9 coverage (2026-10-31) | Phase 10 public fixes (2026-10-31) | 4.4.0 release (2026-11-07) | Phase 12 (local, form members) (2026-11-01) | Phase 12 (local, form members) (2026-11-01) | Phase 12 (local, submission) (2026-11-01) | Phase 12 (local, form members) (2026-11-01) | Phase 12 (local, submission) (2026-11-01) | Phase 12 (local, submission fixes) (2026-11-01) | Phase 12 (local, form members) (2026-11-01) | Phase 12 (local, submission) (2026-11-01) | Phase 12 (local, submission fixes) (2026-11-01) | Phase 12 (local, form members) (2026-11-01) | Phase 12 (local, submission) (2026-11-01) | Phase 12 (local, submission fixes) (2026-11-01) | Phase 12 (local, iframe lifecycle) (2026-11-01) | Phase 12 (local, form members) (2026-11-01) | Phase 12 (local, submission) (2026-11-01) | Phase 12 (local, submission fixes) (2026-11-01) | Phase 12 (local, iframe lifecycle) (2026-11-01) | Phase 12 (local, successful controls) (2026-11-01) | Phase 12 (local, form members) (2026-11-01) | Phase 12 (local, submission) (2026-11-01) | Phase 12 (local, submission fixes) (2026-11-01) | Phase 12 (local, iframe lifecycle) (2026-11-01) | Phase 12 (local, successful controls) (2026-11-01) | Phase 12 (local, submitter) (2026-11-01) | Phase 12 (local, form members) (2026-11-01) | Phase 12 (local, submission) (2026-11-01) | Phase 12 (local, submission fixes) (2026-11-01) | Phase 12 (local, iframe lifecycle) (2026-11-01) | Phase 12 (local, successful controls) (2026-11-01) | Phase 12 (local, submitter) (2026-11-01) | Phase 12 (local, ajaxForm binding) (2026-11-01) | Phase 12 (local, form members) (2026-11-01) | Phase 12 (local, submission) (2026-11-01) | Phase 12 (local, submission fixes) (2026-11-01) | Phase 12 (local, iframe lifecycle) (2026-11-01) | Phase 12 (local, successful controls) (2026-11-01) | Phase 12 (local, submitter) (2026-11-01) | Phase 12 (local, ajaxForm binding) (2026-11-01) | Phase 12 (local, final) (2026-11-01) | 4.5.0 release (2026-11-10) | +| ------------------------------------------------------- | --------------------------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------ | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | +| Test runner | Mocha 7 in PhantomJS via Grunt | Vitest 5 browser mode (Chromium via Playwright) | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | +| Tests | 59 (async tests do not await their assertions) | 64: the same 59, unmodified, plus 5 publish-surface smoke tests | Unchanged | Unchanged | 64: the same 59 rewritten as BDD/AAA with async assertions awaited, plus 5 surface tests | 194: 189 suite (6 are `it.fails` bug records) plus 5 surface tests | 199: 188 suite (6 are `it.fails`), 5 publish-surface, 6 manifest | 204: 192 suite (10 are `it.fails`, 4 new for open issues), 5 publish-surface, 7 manifest and dist (1 `it.fails`) | Unchanged | 206: 194 suite (9 are `it.fails`; the script response record is now an `it`, plus 2 new tests), 5 publish-surface, 7 manifest and dist (1 `it.fails`) | 229: 217 suite (3 are `it.fails`; 6 records are now `it`, plus 23 new tests), 5 publish-surface, 7 manifest and dist (the #553 record is now an `it`) | 245: 233 suite (1 `it.fails`, delegation; the label and #597 records are now `it`, plus 16 new tests), 5 publish-surface, 7 manifest and dist | 790 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` on 3.7.1 (10 records are now `it`, plus 19 new tests), 6 publish-surface (1 new: the classic factory is strict), 7 manifest and dist | 790 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` on 3.7.1 (10 records are now `it`, plus 19 new tests), 6 publish-surface (1 new: the classic factory is strict), 7 manifest and dist | 793 suite per jQuery version, names identical to before the slice (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` unchanged, surfaces unchanged | 790 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` on 3.7.1 (10 records are now `it`, plus 19 new tests), 6 publish-surface (1 new: the classic factory is strict), 7 manifest and dist | 793 suite per jQuery version, names identical to before the slice (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` unchanged, surfaces unchanged | 812 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 35 `it.fails` (58 → 35, 23 flipped), surfaces unchanged | 790 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` on 3.7.1 (10 records are now `it`, plus 19 new tests), 6 publish-surface (1 new: the classic factory is strict), 7 manifest and dist | 793 suite per jQuery version, names identical to before the slice (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` unchanged, surfaces unchanged | 820 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 35 `it.fails` (58 → 35, 23 flipped), surfaces unchanged | 790 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` on 3.7.1 (10 records are now `it`, plus 19 new tests), 6 publish-surface (1 new: the classic factory is strict), 7 manifest and dist | 793 suite per jQuery version, names identical to before the slice (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` unchanged, surfaces unchanged | 820 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 35 `it.fails` (58 → 35, 23 flipped), surfaces unchanged | 831 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 24 `it.fails` (35 → 24, 11 flipped), surfaces unchanged | 790 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` on 3.7.1 (10 records are now `it`, plus 19 new tests), 6 publish-surface (1 new: the classic factory is strict), 7 manifest and dist | 793 suite per jQuery version, names identical to before the slice (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` unchanged, surfaces unchanged | 820 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 35 `it.fails` (58 → 35, 23 flipped), surfaces unchanged | 831 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 24 `it.fails` (35 → 24, 11 flipped), surfaces unchanged | 849 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 17 `it.fails` (23 → 17, 6 flipped), surfaces unchanged | 790 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` on 3.7.1 (10 records are now `it`, plus 19 new tests), 6 publish-surface (1 new: the classic factory is strict), 7 manifest and dist | 793 suite per jQuery version, names identical to before the slice (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` unchanged, surfaces unchanged | 820 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 35 `it.fails` (58 → 35, 23 flipped), surfaces unchanged | 831 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 24 `it.fails` (35 → 24, 11 flipped), surfaces unchanged | 849 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 17 `it.fails` (23 → 17, 6 flipped), surfaces unchanged | 854 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 13 `it.fails` (17 → 13, 4 flipped), surfaces unchanged | 790 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` on 3.7.1 (10 records are now `it`, plus 19 new tests), 6 publish-surface (1 new: the classic factory is strict), 7 manifest and dist | 793 suite per jQuery version, names identical to before the slice (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` unchanged, surfaces unchanged | 820 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 35 `it.fails` (58 → 35, 23 flipped), surfaces unchanged | 831 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 24 `it.fails` (35 → 24, 11 flipped), surfaces unchanged | 849 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 17 `it.fails` (23 → 17, 6 flipped), surfaces unchanged | 854 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 13 `it.fails` (17 → 13, 4 flipped), surfaces unchanged | 880 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 12 `it.fails` (13 → 12, 1 flipped), surfaces unchanged | 790 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` on 3.7.1 (10 records are now `it`, plus 19 new tests), 6 publish-surface (1 new: the classic factory is strict), 7 manifest and dist | 793 suite per jQuery version, names identical to before the slice (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 58 `it.fails` unchanged, surfaces unchanged | 820 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 35 `it.fails` (58 → 35, 23 flipped), surfaces unchanged | 831 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 24 `it.fails` (35 → 24, 11 flipped), surfaces unchanged | 849 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 17 `it.fails` (23 → 17, 6 flipped), surfaces unchanged | 854 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 13 `it.fails` (17 → 13, 4 flipped), surfaces unchanged | 880 suite per jQuery version (1.7.2: 12 skipped; 3.7.1: 1 skipped; 4.0.0: none), 12 `it.fails` (13 → 12, 1 flipped), surfaces unchanged | 900 suite per jQuery version (1.7.2: 14 skipped; 3.7.1: 1 skipped; 4.0.0: none), 2 `it.fails` (12 → 2, 10 flipped), surfaces 5, unchanged | 915 (912 pass, 2 `it.fails` for IFR-122/123, 1 skipped); suite per jQuery version 902 (1.7.2: 14 skipped; 3.7.1: 1 skipped; 4.0.0: none) | +| Suite time | 0.81 s in-browser, 7.0 s wall (`npx grunt mocha`) | 0.53 s in-runner, 0.9 s wall (`npx vitest run`) | Unchanged | Unchanged | 1.15 s in-runner (all projects), includes about 0.6 s of deliberate waits | 3.35 s in-runner (all projects), includes deliberate waits and iframe round trips | 3.35 s in-runner (all projects), 3.8 s wall (`npx vitest run`) | Unchanged | Unchanged | 3.45 s in-runner (all projects), 3.9 s wall (`npx vitest run`) | 3.23 s in-runner (all projects), 3.6 s wall (`npx vitest run`) | 4.69 s wall (`npx vitest run`) | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | 4.5 s in-runner (`npx vitest run --project suite`, jQuery 3.7.1) | 4.75 s in-runner (`npx vitest run --project suite`, jQuery 3.7.1) | +| Full `npm test` | Not defined | 1.5 s wall (lint, build, tests, coverage) | Unchanged | Unchanged | 2.6 s wall | 4.75 s wall | 6.6 s wall | 6.9 s wall | Unchanged | 5.0 s wall | 4.7 s wall | 8.1 s wall | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | 7.0 s wall (lint, format check, build, Vitest with coverage) | 7.8 s wall | +| Line coverage of `src` | Not measured by the toolchain (about 60% under the prototype runners) | 35.4% | Unchanged | Unchanged | 35.95% | 98.14% | 98.13% | Unchanged | Unchanged | 100% | Unchanged | Unchanged | 100% (`src/*.js`, 2 files) | 100% (`src/*.js`, 2 files) | 100% (`src/*.js`, 7 files) | 100% (`src/*.js`, 2 files) | 100% (`src/*.js`, 7 files) | 100% (`src/*.js`, 7 files) | 100% (`src/*.js`, 2 files) | 100% (`src/*.js`, 7 files) | 100% (`src/*.js`, 7 files) | 100% (`src/*.js`, 2 files) | 100% (`src/*.js`, 7 files) | 100% (`src/*.js`, 7 files) | 100% (`src/*.js`, 10 files) | 100% (`src/*.js`, 2 files) | 100% (`src/*.js`, 7 files) | 100% (`src/*.js`, 7 files) | 100% (`src/*.js`, 10 files) | 100% (`src/*.js`, 12 files) | 100% (`src/*.js`, 2 files) | 100% (`src/*.js`, 7 files) | 100% (`src/*.js`, 7 files) | 100% (`src/*.js`, 10 files) | 100% (`src/*.js`, 12 files) | 100% (`src/*.js`, 13 files) | 100% (`src/*.js`, 2 files) | 100% (`src/*.js`, 7 files) | 100% (`src/*.js`, 7 files) | 100% (`src/*.js`, 10 files) | 100% (`src/*.js`, 12 files) | 100% (`src/*.js`, 13 files) | 100% (`src/*.js`, 14 files) | 100% (`src/*.js`, 2 files) | 100% (`src/*.js`, 7 files) | 100% (`src/*.js`, 7 files) | 100% (`src/*.js`, 10 files) | 100% (`src/*.js`, 12 files) | 100% (`src/*.js`, 13 files) | 100% (`src/*.js`, 14 files) | 100% (`src/*.js`, 14 files) | 100% | +| Branch coverage of `src` | Not measured (about 53% under the prototype runners) | 33.9% | Unchanged | Unchanged | Unchanged | 96.41% | 96.40% | Unchanged | Unchanged | 100% | Unchanged | Unchanged | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | +| Function coverage of `src` | Not measured | Not recorded | Unchanged | Unchanged | 43.10% | 98.27% | 98.24% | Unchanged | Unchanged | 100% | Unchanged | Unchanged | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | +| Statement coverage of `src` | Not measured | Not recorded | Unchanged | Unchanged | 36.77% | 98.17% | 98.16% | Unchanged | Unchanged | 100% | Unchanged | Unchanged | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | 100% | +| Coverage enforced | No | No (reported on every run) | Unchanged | Unchanged | Unchanged | Yes: lines 98.14%, branches 96.41%, functions 98.27%, statements 98.17% | Yes: lines 98.13%, branches 96.4%, functions 98.24%, statements 98.16% (same uncovered code; the `eval` fallback is gone) | Unchanged | Unchanged | Yes: 100% on all four | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | +| `dist/jquery.form.min.js` | 17.09 kB min, 6.57 kB gzip | 17.18 kB min, 6.57 kB gzip | Unchanged | Unchanged | Unchanged | Unchanged | 17.15 kB min, 6.55 kB gzip | Unchanged | Unchanged | 16.70 kB min, 6.38 kB gzip | 17.10 kB min, 6.57 kB gzip | 17.45 kB min, 6.67 kB gzip | 18.08 kB min, 7.00 kB gzip | 18.08 kB min, 7.00 kB gzip | 18.93 kB min, 7.36 kB gzip | 18.08 kB min, 7.00 kB gzip | 18.93 kB min, 7.36 kB gzip | 19.40 kB min, 7.51 kB gzip | 18.08 kB min, 7.00 kB gzip | 18.93 kB min, 7.36 kB gzip | 20.25 kB min, 7.80 kB gzip | 18.08 kB min, 7.00 kB gzip | 18.93 kB min, 7.36 kB gzip | 20.25 kB min, 7.80 kB gzip | 21.41 kB min, 8.14 kB gzip | 18.08 kB min, 7.00 kB gzip | 18.93 kB min, 7.36 kB gzip | 20.25 kB min, 7.80 kB gzip | 21.41 kB min, 8.14 kB gzip | 22.26 kB min, 8.46 kB gzip | 18.08 kB min, 7.00 kB gzip | 18.93 kB min, 7.36 kB gzip | 20.25 kB min, 7.80 kB gzip | 21.41 kB min, 8.14 kB gzip | 22.26 kB min, 8.46 kB gzip | 22.88 kB min, 8.70 kB gzip | 18.08 kB min, 7.00 kB gzip | 18.93 kB min, 7.36 kB gzip | 20.25 kB min, 7.80 kB gzip | 21.41 kB min, 8.14 kB gzip | 22.26 kB min, 8.46 kB gzip | 22.88 kB min, 8.70 kB gzip | 23.92 kB min, 9.02 kB gzip | 18.08 kB min, 7.00 kB gzip | 18.93 kB min, 7.36 kB gzip | 20.25 kB min, 7.80 kB gzip | 21.41 kB min, 8.14 kB gzip | 22.26 kB min, 8.46 kB gzip | 22.88 kB min, 8.70 kB gzip | 23.92 kB min, 9.02 kB gzip | 25.49 kB min, 9.59 kB gzip | 25.58 kB min, 9.63 kB gzip | +| `npm audit` | 51 (11 critical, 25 high, 10 moderate, 5 low) | 0 | Unchanged | Unchanged | Unchanged | Unchanged | 0 vulnerabilities | Unchanged | Unchanged | Unchanged | 6 moderate, dev only (`minimatch` via ESLint, GHSA-g3hv-75wg-m249); 0 with `--omit=dev` | 0 (`minimatch` override, PR #638) | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | 0 | +| Dev dependencies (direct) | 8 | 15 | Unchanged | Unchanged | Unchanged | Unchanged | 15 (no upgrades were available; see `docs/research/jquery-matrix.md`) | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | +| jQuery versions tested | 3.5.1 only (from the CDN) | 3.7.1 (suite and surfaces), 4.0.0 (ESM surface only) | Unchanged | Unchanged | Unchanged | Unchanged | 1.7.2, 3.7.1 and 4.0.0, all gating in CI; the ESM surface test also loads 4.0.0 | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged (plus a slim-build fixture for 3.7.1 and 4.0.0) | Unchanged | Unchanged | Unchanged (plus a slim-build fixture for 3.7.1 and 4.0.0) | Unchanged | Unchanged | Unchanged (plus a slim-build fixture for 3.7.1 and 4.0.0) | Unchanged | Unchanged | Unchanged | Unchanged (plus a slim-build fixture for 3.7.1 and 4.0.0) | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged (plus a slim-build fixture for 3.7.1 and 4.0.0) | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged (plus a slim-build fixture for 3.7.1 and 4.0.0) | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged (plus a slim-build fixture for 3.7.1 and 4.0.0) | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | +| CI | Travis and CircleCI configs (inactive) | GitHub Actions (duration recorded after the first run on `main`) | 6 warm runs, median (min–max); 1 cold run. Steps below | 6 warm runs, 1 cold run; steps below | Unchanged | 1 warm run; steps below | Run 40992583331 (warm); the `jquery` matrix jobs run in parallel with `test` | Run 40999832492 (PR, warm) | Run 41227104628 (PR, warm) | Run 41258062402 (PR, warm) | Run 41263541622 (PR, warm) | Run 42332118377 (release PR, warm) | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | Run 42496815963 (release PR before the version bump, warm) | +| Open issues / PRs | 27 / 8 | 27 / 8 | 27 / 8 | 27 / 8 | Unchanged | 27 / 9 (includes PR #626) | 27 / 9 (includes PR #627) | 12 / 3 (15 issues and 5 PRs closed; closures posted 2026-10-30) | 13 / 1 (#629 opened; PRs #586 and #611 closed) | Unchanged | Unchanged | Unchanged until the release closures | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | 5 / 2 before the release closures | +| CI queue time | — | — | 3 s (2–3 s) | 3 s (2–3 s) | Unchanged | 3 s | 2 s | 3 s | 3 s | 3 s | 3 s | 2 s | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | 2 s | +| CI total wall time | — | — | 31 s (27–33 s); cold 32 s | 27 s (22–31 s); cold 36 s | Unchanged | 35 s | 31 s (`test` job) | 29 s (`test` job) | 26 s (`test` job) | 27 s (`test` job) | 32 s (`test` job) | 30 s (`test` job) | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | 33 s (`test` job) | +| CI step: setup-node (npm cache) | — | — | 6.5 s (5–8 s); cold 5 s | 6.5 s (6–7 s); cold 6 s | Unchanged | 7 s | 6 s | 5 s | 5 s | 6 s | 5 s | 5 s | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | 5 s | +| CI step: `npm ci` | — | — | 1 s (1–2 s); cold 2 s | 1 s (0–2 s); cold 2 s | Unchanged | 2 s | 2 s | 2 s | 1 s | 1 s | 2 s | 2 s | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | 2 s | +| CI step: Playwright Chromium install | — | — | 8 s (7–10 s); cold 10 s | 1 s (0–1 s) plus 3 s cache restore; cold 10 s plus 4 s cache save | Unchanged | 1 s plus 4 s cache restore | 1 s (cache 3 s) | 1 s (cache 3 s) | 1 s (cache 2 s) | 1 s (cache 3 s) | 0 s (cache 3 s) | 1 s (cache 3 s) | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | 1 s (cache 2 s) | +| CI step: lint | — | — | 1 s (0–1 s) | 0 s (0–1 s) | Unchanged | 1 s | 1 s | 1 s | 1 s | 0 s | 1 s | 1 s | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | 2 s | +| CI step: format check | — | — | 1 s (0–1 s) | 1 s (1–2 s) | Unchanged | 1 s | 1 s | 2 s | 1 s | 1 s | 2 s | 1 s | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | 2 s | +| CI step: build | — | — | 0.5 s (0–1 s) | 1 s (0–1 s) | Unchanged | 1 s | 1 s | 0 s | 1 s | 1 s | 1 s | 1 s | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | 1 s | +| CI step: Vitest with coverage | — | — | 3 s (3–4 s) | 2.5 s (1–4 s) | Unchanged | 6 s | 6 s | 7 s | 6 s | 5 s | 8 s | 8 s | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | 9 s | +| CI step: checkout, job setup, dist check, report upload | — | — | about 1 s each | about 1 s each | Unchanged | 0–2 s each | 0–1 s each | 0–1 s each | 0–1 s each | 0–1 s each | 0–2 s each | 0–1 s each | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | not re-measured | 0–1 s each | +| Source lines: physical / code / comment-only | 1592 / 1050 / 289 | — | — | — | — | — | — | — | 1562 / 1029 / 279 | 1529 / 999 / 278 | 1584 / 1029 / 292 | 1607 / 1040 / 300 | 1696 / 1086 / 321 (2 files) | 1696 / 1086 / 321 (2 files) | 1844 / 1159 / 367 (7 files) | 1696 / 1086 / 321 (2 files) | 1844 / 1159 / 367 (7 files) | 1958 / 1231 / 386 (7 files) | 1696 / 1086 / 321 (2 files) | 1844 / 1159 / 367 (7 files) | 2023 / 1279 / 391 (7 files) | 1696 / 1086 / 321 (2 files) | 1844 / 1159 / 367 (7 files) | 2023 / 1279 / 391 (7 files) | 2266 / 1432 / 432 (10 files) | 1696 / 1086 / 321 (2 files) | 1844 / 1159 / 367 (7 files) | 2023 / 1279 / 391 (7 files) | 2266 / 1432 / 432 (10 files) | 2407 / 1495 / 476 (12 files) | 1696 / 1086 / 321 (2 files) | 1844 / 1159 / 367 (7 files) | 2023 / 1279 / 391 (7 files) | 2266 / 1432 / 432 (10 files) | 2407 / 1495 / 476 (12 files) | 2517 / 1555 / 502 (13 files) | 1696 / 1086 / 321 (2 files) | 1844 / 1159 / 367 (7 files) | 2023 / 1279 / 391 (7 files) | 2266 / 1432 / 432 (10 files) | 2407 / 1495 / 476 (12 files) | 2517 / 1555 / 502 (13 files) | 2629 / 1642 / 502 (14 files) | 1696 / 1086 / 321 (2 files) | 1844 / 1159 / 367 (7 files) | 2023 / 1279 / 391 (7 files) | 2266 / 1432 / 432 (10 files) | 2407 / 1495 / 476 (12 files) | 2517 / 1555 / 502 (13 files) | 2629 / 1642 / 502 (14 files) | 2703 / 1687 / 516 (14 files) | 2704 / 1688 / 516 (14 files) | +| Functions | 60 | — | — | — | — | — | — | — | 57 | 56 | 62 | 64 | 74 | 74 | 87 | 74 | 87 | 94 | 74 | 87 | 96 | 74 | 87 | 96 | 128 | 74 | 87 | 96 | 128 | 146 | 74 | 87 | 96 | 128 | 146 | 155 | 74 | 87 | 96 | 128 | 146 | 155 | 164 | 74 | 87 | 96 | 128 | 146 | 155 | 164 | 169 | 169 | +| Cyclomatic complexity: total / mean / max | 417 / 6.95 / 62 | — | — | — | — | — | — | — | 407 / 7.14 / 62 | 386 / 6.89 / 54 | 400 / 6.45 / 52 | 407 / 6.36 / 52 | 421 / 5.69 / 52 | 421 / 5.69 / 52 | 434 / 4.99 / 48 (`ajaxSubmit` 52 → 4) | 421 / 5.69 / 52 | 434 / 4.99 / 48 (`ajaxSubmit` 52 → 4) | 462 / 4.91 / 48 | 421 / 5.69 / 52 | 434 / 4.99 / 48 (`ajaxSubmit` 52 → 4) | 474 / 4.94 / 48 | 421 / 5.69 / 52 | 434 / 4.99 / 48 (`ajaxSubmit` 52 → 4) | 474 / 4.94 / 48 | 510 / 3.98 / 37 | 421 / 5.69 / 52 | 434 / 4.99 / 48 (`ajaxSubmit` 52 → 4) | 474 / 4.94 / 48 | 510 / 3.98 / 37 | 537 / 3.68 / 15 | 421 / 5.69 / 52 | 434 / 4.99 / 48 (`ajaxSubmit` 52 → 4) | 474 / 4.94 / 48 | 510 / 3.98 / 37 | 537 / 3.68 / 15 | 558 / 3.60 / 15 | 421 / 5.69 / 52 | 434 / 4.99 / 48 (`ajaxSubmit` 52 → 4) | 474 / 4.94 / 48 | 510 / 3.98 / 37 | 537 / 3.68 / 15 | 558 / 3.60 / 15 | 583 / 3.55 / 15 | 421 / 5.69 / 52 | 434 / 4.99 / 48 (`ajaxSubmit` 52 → 4) | 474 / 4.94 / 48 | 510 / 3.98 / 37 | 537 / 3.68 / 15 | 558 / 3.60 / 15 | 583 / 3.55 / 15 | 597 / 3.53 / 15 | 597 / 3.53 / 15 | +| Functions with complexity > 10 | 10 | — | — | — | — | — | — | — | 10 | 10 | Unchanged | 10 | Unchanged | Unchanged | 9 | Unchanged | 9 | 10 | Unchanged | 9 | 10 | Unchanged | 9 | 10 | 9 | Unchanged | 9 | 10 | 9 | 9 | Unchanged | 9 | 10 | 9 | 9 | 9 | Unchanged | 9 | 10 | 9 | 9 | 9 | 9 | Unchanged | 9 | 10 | 9 | 9 | 9 | 9 | 9 | 9 | +| Max block nesting depth | 5 | — | — | — | — | — | — | — | 5 | 5 | Unchanged | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 6 | 5 | 6 | 6 | 6 | 5 | 5 | 6 | 6 | 6 | 5 | 5 | 5 | 6 | 6 | 6 | 5 | 5 | 5 | 5 | 6 | 6 | 6 | 5 | 5 | 5 | 5 | 5 | 5 | +| Public API: `$.fn` / `$` members | 14 / 1 | — | — | — | — | — | — | — | 14 / 1 | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged (`ajaxFormUnbind` takes an optional selector) | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged (`ajaxFormUnbind` takes an optional selector) | Unchanged | Unchanged | +| CodeQL alerts (open) | — | — | — | — | — | — | — | — | 3 in `src/` on `main` (alerts 1, 4 and 7) | Unchanged | Unchanged (the PR adds none) | 1 expected (alert 7, `iframeTarget`); alerts 1 and 4 close | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | Unchanged | 0 (alert 10, the `target` lookup moved by the module split, dismissed; 4.6.0 removes it) | How measured: CI timings from `scripts/ci-timings.sh ` (GitHub job step timestamps, whole seconds) over run 40225846996 (Phase 3B baseline; the Playwright cache column is run 40227654269, attempt 1 cold and attempts 2–7 warm; the Phase 5 column is run 40233863662, attempt 1, warm), attempts 3–8 warm (npm cache hit) and attempt 2 cold (after `gh cache delete --all`); suite time from runner output and `time`; coverage from `npm test` (v8); gzip via `gzip -c | wc -c`; issue and PR counts via `gh issue list` and `gh pr list`. @@ -46,3 +46,19 @@ The prototype coverage figures included two extra upload tests (iframe transport Source metrics come from `npm run metrics` (v4.3.0: `npm run metrics -- v4.3.0`). It formats the source with the repo's Prettier config before counting, so tabs versus spaces don't affect the numbers. Complexity and nesting come from ESLint's `complexity` and `max-depth` rules. The v4.3.0 source includes its UMD wrapper and the `eval` JSON fallback, which account for most of the function difference. Phase 6 times are from `npm test` and `npx vitest run` on the same machine. The Phase 7, 8, 9 and 10 CI columns are one warm run each: the last PR run of the phase, read afterwards with `scripts/ci-timings.sh`. Phase 9 local times are medians of 5 runs after a warm-up run (spread under 0.2 s). Phase 10 local times are medians of 3 runs (spread under 0.1 s). The suite is gated on jQuery 3.7.1 only; see `docs/research/jquery-matrix.md` for the per-version results. + +The Phase 12 column is the local `phase-12` branch after the form-members slice, measured with `npm test` and the suite on each jQuery version. `npm run metrics` now sums every `src/*.js` file and labels hot spots `file:line`; a ref with one source file is measured as before. Just before the slice (829b8a2) the source measured 1607 / 1040 / 300 lines, 64 functions, complexity 407 / 6.36 / 52 and nesting depth 6, so the depth of 6 predates the slice. + +The Phase 12 (local, submission) column is the same branch after the Submission refactor (`src/options.js`, `src/diagnostics.js`, `src/submission.js`, `src/xhr-transport.js`, `src/iframe-transport.js`); behavior is unchanged. Just before it (3160302) the source measured 1708 / 1092 / 323 lines, 74 functions, complexity 425 / 5.74 / 52 and 10 functions above 10. The largest functions are now the iframe response handler `cb` (48, `src/iframe-transport.js`), `formToArray` (37), `fieldValue` (28), `fileUploadIframe` (26) and `doSubmit` (20). + +The Phase 12 (local, submission fixes) column is the same branch after the submission fixes (url `false`/`""`, callback arrays, empty `target`, `context`, one request method, string `data`, the slim-build error, `requestFormat: "json"`), measured the same way. + +The Phase 12 (local, iframe lifecycle) column is the same branch after the iframe adapter split (`src/iframe-response.js`, `src/iframe-post.js`, `src/iframe-lifecycle.js`, with `src/iframe-transport.js` as the adapter) and the lifecycle fixes (D-08, D-07, D-16, D-22, D-21, D-33). The iframe response handler `cb` went from 48 to 7, `fileUploadIframe` from 27 to 4 and `doSubmit` from 22 to 5; the largest functions are now `formToArray` (37), `fieldValue` (28), `httpData` (15, `src/iframe-response.js`), the `clearFields` loop (13) and `chooseTransport` (13, `src/submission.js`). + +The Phase 12 (local, submitter) column is the same branch after the submitter slice (`src/submitter.js`: a private store, the `clk` expandos as a written and read fallback, `SubmitEvent.submitter` when no click was captured; SER-38, AJF-57, AJF-68, XHR-77). The largest functions are unchanged (`httpData` 15, `$.fn.clearFields`' loop 13, `chooseTransport` 13). + +The Phase 12 (local, ajaxForm binding) column is the same branch after the binding slice (`src/ajax-form.js`; `delegation: ""` with its own document handlers, `ajaxFormUnbind()` and `ajaxFormUnbind(selector)` removing delegated bindings, the `delegation: true` warning on jQuery 3 and later). `ajaxForm` itself went from 14 to 8; the largest functions are unchanged (`httpData` 15, `$.fn.clearFields`' loop 13, `chooseTransport` 13). + +The Phase 12 (local, final) column is the same branch after the last Phase 12 commits: debug-only deprecation warnings (`clearInputs`, `attr2`, the DOM-not-ready `ajaxForm` queue, the automatic iframe transport, jQuery before 3.5), the `target` sanitizing, trusted-options and iframe-response docs, and the remaining fixes (D-12, D-13, D-15, D-19, D-25, the FormData `beforeSend` veto). Times are from `npm test` (without the untracked probe files) and the suite project on jQuery 3.7.1, one warm run each on Node v26.12.1. + +The 4.5.0 release column is the `release-4.5.0` branch with the version bump. Times are from `npm test` and the suite project on each jQuery version, one warm run each on Node v26.12.1. The CI rows are the last PR run before the bump, which changed only the version strings. CodeQL alert 10 was dismissed on 2026-11-10 because the `target` and `iframeTarget` options are trusted input; 4.6.0 looks their strings up only as selectors. diff --git a/docs/options.md b/docs/options.md index 7fd688e..f265e6c 100644 --- a/docs/options.md +++ b/docs/options.md @@ -56,6 +56,17 @@ Expected data type of the response. One of: null, 'xml', 'script', or 'json'. Th **'script'**: if dataType == 'script' the server response is evaluated in the global context +### delegation + +Default: `undefined` +A selector string, or `true`, to handle forms through a binding on the document, so forms added later are handled too (`ajaxForm` only; requires jQuery 1.7+). With a selector, a form is submitted through the plugin when it, or an element around it, matches the selector; the selection is ignored, and binding the same selector again replaces its options. An empty string throws an error. `ajaxFormUnbind()` removes every delegated binding; `ajaxFormUnbind(selector)` removes one. + +```javascript +$(document).ajaxForm({ delegation: "form.ajax" }); +``` + +**Warning:** `delegation: true` binds **every form on the page** on jQuery 3 and later (jQuery 3.0 removed the selector it relied on), so the options (`data`, `headers`) go with any form's submission. The plugin logs a `console.warn` for each such call, even with `debug` off. Use a selector. + ### error Callback function to be invoked upon error. It is passed the following arguments: @@ -75,6 +86,15 @@ Boolean value. Set to true to remove short delay before posting form when upload Default: `false` Boolean flag indicating whether the form should always target the server response to an iframe. This is useful in conjuction with file uploads. See the _File Uploads_ documentation on the [Code Samples](#code-samples) page for more info. +Without `FormData`, a form with a selected file or a multipart `enctype` also uses the iframe. Choosing it automatically is deprecated (a `debug` warning); 5.0 uses the iframe only when `iframe: true` is set. + +The response is loaded as a document in the hidden iframe, with the same origin as the page, before the plugin reads it. The server must return a response that is safe to render as HTML: + +- Send JSON and text as `text/plain`, or wrap them in a `' + ).find(":input"); + $fields.eq(0).prop("checked", false); + $fields.eq(1).val("changed"); + $fields.eq(2).val("changed"); + + $fields.resetForm(); + + assert.strictEqual($fields.eq(0).prop("checked"), true); + assert.strictEqual($fields.eq(1).val(), "original"); + assert.strictEqual($fields.eq(2).val(), "original"); + }); + + it("should restore a multiple select when resetting an optgroup", function () { + const $select = $( + "" + ); + const $options = $select.find("option"); + $options.eq(0).prop("selected", false); + $options.eq(1).prop("selected", true); + + $select.find("optgroup").resetForm(); + + assert.deepEqual( + $options + .map(function () { + return this.selected; + }) + .get(), + [true, false] + ); + }); + + it("should reset form controls found inside a container", function () { + const $container = $( + '
' + ); + $container.find("input").val("changed"); + $container.find("select").val("two"); + + $container.resetForm(); + + assert.strictEqual($container.find("input").val(), "original"); + assert.strictEqual($container.find("select").val(), "one"); + }); + + it("should return the original set and ignore arguments when resetting", function () { + const $container = $('
'); + $container.find("input").val("changed"); + + const result = $container.resetForm("ignored"); + + assert.strictEqual(result, $container); + assert.strictEqual($container.find("input").val(), "original"); + }); + + it("should leave fields unchanged and return the set when a reset handler prevents the default", function () { + const $form = $('
').appendTo("#main"); + $form.on("reset", (event) => event.preventDefault()); + $form.find("input").val("changed"); + + const result = $form.resetForm(); + + assert.strictEqual(result, $form); + assert.strictEqual($form.find("input").val(), "changed"); + }); + + it("should restore checked and value when an input is reset directly", function () { + const $inputs = $( + '
' + ).find("input"); + $inputs.eq(0).prop("checked", false); + $inputs.eq(1).prop("checked", true); + + $inputs.resetForm(); + + assert.strictEqual($inputs.eq(0).prop("checked"), true); + assert.strictEqual($inputs.eq(0).val(), "a"); + assert.strictEqual($inputs.eq(1).prop("checked"), false); + assert.strictEqual($inputs.eq(1).val(), "b"); + }); + + it("should keep a checkbox's value on when the checkbox is reset outside a form", function () { + const $container = $('
'); + + $container.resetForm(); + + assert.strictEqual($container.find("input").val(), "on"); + }); + + it("should keep a submit input's default label when it is reset in a container", function () { + const $container = $('
'); + + $container.resetForm(); + + assert.isFalse($container.find("input")[0].hasAttribute("value")); + }); + + it("should not throw when a file input with a value attribute is reset", function () { + const $file = $(''); + + const reset = () => $file.resetForm(); + + assert.doesNotThrow(reset); + }); + + it("should empty a selected file input when it is reset", function () { + const $file = $(''); + selectFiles($file[0], ["a.txt"]); + + $file.resetForm(); + + assert.strictEqual($file[0].files.length, 0); + }); + + it("should leave a hidden input's scripted value when it is reset", function () { + const $hidden = $(''); + $hidden.val("scripted"); + + $hidden.resetForm(); + + assert.strictEqual($hidden.val(), "scripted"); + }); + + it("should restore only that option when an option of a multiple select is reset", function () { + const $options = $( + "" + ).find("option"); + $options.eq(0).prop("selected", false); + $options.eq(1).prop("selected", true); + + $options.eq(0).resetForm(); + + assert.deepEqual(selectedStates($options), [true, true]); + }); + + it("should reset the parent single select when an optgroup is reset", function () { + const $select = $( + "" + ); + $select.val("c"); + + $select.find("optgroup").resetForm(); + + assert.strictEqual($select.val(), "b"); + }); + + it("should leave an option outside any select unchanged when it is reset", function () { + const option = $('').find("option")[0]; + option.selected = true; + + $(option).resetForm(); + + assert.strictEqual(option.selected, true); + }); + + it("should select the last default option when a single select with two default options is reset", function () { + const $select = $( + "" + ); + $select.val("c"); + + $select.resetForm(); + + assert.strictEqual($select.val(), "b"); + }); + + it("should select the first option of a dropdown and none of a list box when no option is a default", function () { + const $dropdown = $(""); + const $listBox = $(''); + $dropdown.val("b"); + $listBox.val("b"); + + $dropdown.add($listBox).resetForm(); + + assert.strictEqual($dropdown.val(), "a"); + assert.strictEqual($listBox[0].selectedIndex, -1); + }); + + it("should restore every option when a multiple select is reset directly", function () { + const $select = $( + "" + ); + const $options = $select.find("option"); + $options.prop("selected", false); + $options.eq(1).prop("selected", true); + + $select.resetForm(); + + assert.deepEqual(selectedStates($options), [true, false, true]); + }); + + it("should leave the inputs inside a non-control named by a label's for attribute unchanged", function () { + const $owner = $('
').appendTo("#main"); + const $label = $('').appendTo("#main"); + $owner.find("input").val("changed"); + + $label.resetForm(); + + assert.strictEqual($owner.find("input").val(), "changed"); + }); + + it("should reset the document's control when a detached label names it", function () { + const $target = $('').appendTo("#main"); + const $label = $(''); + $target.val("changed"); + + $label.resetForm(); + + assert.strictEqual($target.val(), "default"); + }); + + it("should reset a control outside the container when a label inside names it", function () { + const $outside = $('').appendTo("#main"); + const $container = $('
').appendTo( + "#main" + ); + $outside.val("changed"); + + $container.resetForm(); + + assert.strictEqual($outside.val(), "default"); + }); + + it("should reset a control associated by the form attribute when its form is reset", function () { + $('
').appendTo( + "#main" + ); + const $outside = $("#main input[form=native-owner]").val("changed"); + + $("#native-owner").resetForm(); + + assert.strictEqual($outside.val(), "default"); + }); + + it("should reset the form when two controls named reset shadow the method", function () { + const $form = $( + '
' + ).appendTo("#main"); + $form.find("input").eq(0).val("changed"); + + const reset = () => $form.resetForm(); + + assert.doesNotThrow(reset); + assert.strictEqual($form.find("input").eq(0).val(), "a"); + }); + + it("should reset natively when a control named tagName shadows the form's tag name", function () { + $( + '
' + ).appendTo("#main"); + const $form = $("#tag-owner"); + const $outside = $("#main input[form=tag-owner]").val("changed"); + let resets = 0; + $form.on("reset", () => resets++); + + $form.resetForm(); + + assert.strictEqual(resets, 1); + assert.strictEqual($outside.val(), "default"); + }); + + it("should reset a nested form natively when a container is reset", function () { + const $container = $('
').appendTo("#main"); + let resets = 0; + $container.find("form").on("reset", () => resets++); + $container.find("input").val("changed"); + + $container.resetForm(); + + assert.strictEqual(resets, 1); + assert.strictEqual($container.find("input").val(), "default"); + }); + + it("should still reset a nested form's controls when its reset event is cancelled and a container is reset", function () { + const $container = $('
').appendTo("#main"); + $container.find("form").on("reset", (event) => event.preventDefault()); + $container.find("input").val("changed"); + + $container.resetForm(); + + assert.strictEqual($container.find("input").val(), "default"); + }); + + it("should not throw when resetting the window", function () { + const $window = $(window); + + const reset = () => $window.resetForm(); + + assert.doesNotThrow(reset); + }); + + it("should not fire change or input events when resetting fields individually", function () { + const $container = $( + '
' + ).appendTo("#main"); + $container.find("input").eq(0).val("changed"); + $container.find("input").eq(1).prop("checked", false); + $container.find("select").val("b"); + $container.find("textarea").val("changed"); + + const events = recordFieldEvents($container[0], () => $container.resetForm()); + + assert.deepEqual(events, []); + assert.strictEqual($container.find("select").val(), "a"); + }); + + it("should reset disabled and readonly fields", function () { + const $fields = $('
').find( + "input" + ); + $fields.val("changed"); + + $fields.resetForm(); + + assert.strictEqual($fields.eq(0).val(), "a"); + assert.strictEqual($fields.eq(1).val(), "b"); + }); + }); + + describe("clearForm", function () { + it("should empty a text input", function () { + const $el = $("#form1 input[name=Name]"); + assert.ok("MyName1" == $el.val(), "beforeSubmit: " + $el.val()); + + $("#form1").clearForm(); + + assert.ok("" == $el.val(), "success: " + $el.val()); + }); + + it("should deselect a select", function () { + const $el = $("#form1 select[name=Single]"); + assert.ok("one" == $el.val(), "beforeSubmit: " + $el.val()); + + $("#form1").clearForm(); + + assert.ok(!$el.val(), "success: " + $el.val()); + }); + + it("should leave a hidden input unchanged", function () { + const $el = $("#form1 input:hidden"); + assert.ok("hiddenValue" == $el.val(), "beforeSubmit: " + $el.val()); + + $("#form1").clearForm(); + + assert.ok("hiddenValue" == $el.val(), "success: " + $el.val()); + }); + + it("should leave a submit input unchanged", function () { + const $el = $("#form1 input:submit"); + assert.ok("Submit1" == $el.val(), "beforeSubmit: " + $el.val()); + + $("#form1").clearForm(); + + assert.ok("Submit1" == $el.val(), "success: " + $el.val()); + }); + + it("should uncheck a checkbox", function () { + const el = $("#form1 input:checkbox:checked")[0]; + assert.ok(el.checked, "beforeSubmit: " + el.checked); + + $("#form1").clearForm(); + + assert.ok(!el.checked, "success: " + el.checked); + }); + + it("should uncheck a radio button", function () { + const el = $("#form1 input:radio:checked")[0]; + assert.ok(el.checked, "beforeSubmit: " + el.checked); + + $("#form1").clearForm(); + + assert.ok(!el.checked, "success: " + el.checked); + }); + + it("should clear hidden inputs only when explicitly included", function () { + const $fields = $( + '
' + ).find("input"); + + $fields.clearFields(".special:hidden"); + + assert.strictEqual($fields.eq(0).val(), "plain"); + assert.strictEqual($fields.eq(1).val(), ""); + }); + + // #600: the document and text nodes have no tag name. + it("should skip nodes without a tag name", function () { + const $nodes = $([document, document.createTextNode("text")]); + + const clear = () => $nodes.clearFields(); + + assert.doesNotThrow(clear); + }); + + it("should clear all hidden inputs when includeHidden is true", function () { + const $hidden = $(''); + + $hidden.clearFields(true); + + assert.strictEqual($hidden.val(), ""); + }); + + it("should clear a file input without replacing it in modern browsers", function () { + const $file = $(''); + const file = $file[0]; + + const result = $file.clearFields(); + + assert.strictEqual(result[0], file); + assert.strictEqual($file.val(), ""); + }); + + it("should replace a file input when simulating legacy MSIE", function () { + const userAgent = Object.getOwnPropertyDescriptor(navigator, "userAgent"); + const $container = $('
'); + const file = $container.find("input")[0]; + Object.defineProperty(navigator, "userAgent", { + configurable: true, + value: "MSIE 10.0", + }); + + try { + $(file).clearFields(); + + assert.notStrictEqual($container.find("input")[0], file); + assert.strictEqual($container.find("input").attr("name"), "upload"); + } finally { + if (userAgent) { + Object.defineProperty(navigator, "userAgent", userAgent); + } else { + delete navigator.userAgent; + } + } + }); + + it("should return the original set when clearing forms, containers, inputs or empty sets", function () { + const sets = [$("
"), $("
"), $(""), $()]; + + const results = sets.map(($set) => $set.clearForm()); + + results.forEach((result, i) => assert.strictEqual(result, sets[i])); + }); + + it("should clear fields inside a non-form container", function () { + const $container = $( + '
' + ); + + $container.clearForm(); + + assert.strictEqual($container.find("input").eq(0).val(), ""); + assert.strictEqual($container.find("textarea").val(), ""); + assert.strictEqual($container.find("input").eq(1).prop("checked"), false); + }); + + it("should clear hidden inputs when clearForm is passed true or a selector", function () { + const $all = $('
'); + const $some = $( + '
' + ); + + $all.clearForm(true); + $some.clearForm(".special"); + + assert.strictEqual($all.find("input").val(), ""); + assert.strictEqual($some.find("input").eq(0).val(), ""); + assert.strictEqual($some.find("input").eq(1).val(), "c"); + }); + + it("should leave an input unchanged when clearForm is called on the input itself", function () { + const $input = $(''); + + $input.clearForm(); + + assert.strictEqual($input.val(), "kept"); + }); + + it("should leave a control associated by the form attribute unchanged when its form is cleared", function () { + $('
').appendTo( + "#main" + ); + + $("#clear-owner").clearForm(); + + assert.strictEqual($("#main input[form=clear-owner]").val(), "outside"); + }); + + it("should never clear button or output elements", function () { + const $container = $('
o
'); + + $container.clearForm("button,output"); + + assert.strictEqual($container.find("button").val(), "b"); + assert.strictEqual($container.find("output")[0].value, "o"); + }); + + it("should clear every field on the page when called on the document and skip the window and text nodes", function () { + const $input = $('').appendTo("#main"); + const $nodes = $([document, window, document.createTextNode("text")]); + + const clear = () => $nodes.clearForm(); + + assert.doesNotThrow(clear); + assert.strictEqual($input.val(), ""); + }); + + it("should pass includeHidden to clearForm when ajaxSubmit clears the form", async function () { + const $form = $( + '
' + ).appendTo("#main"); + + await withAjaxStub( + function (options) { + options.success("ok", "success", {}); + return {}; + }, + async function () { + $form.ajaxSubmit({ clearForm: true, includeHidden: true }); + await Promise.resolve(); + } + ); + + assert.strictEqual($form.find("input").val(), ""); + }); + + it("should return the original set when clearing fields", function () { + const $fields = $(''); + + const result = $fields.clearFields(); + + assert.strictEqual(result, $fields); + }); + + [ + ["date", "2024-01-02"], + ["email", "a@example.com"], + ["month", "2024-01"], + ["number", "5"], + ["password", "pw"], + ["search", "s"], + ["tel", "1"], + ["text", "t"], + ["time", "10:00"], + ["url", "https://example.com/"], + ["week", "2024-W01"], + ].forEach(function ([type, value]) { + it("should empty a " + type + " input when clearing fields", function () { + const $input = $('').val(value); + + $input.clearFields(); + + assert.strictEqual($input.val(), ""); + }); + }); + + it("should leave range at its midpoint and color at black when they are cleared", function () { + const $range = $(''); + const $color = $(''); + + $range.add($color).clearFields(); + + assert.strictEqual($range.val(), "50"); + assert.strictEqual($color.val(), "#000000"); + }); + + it("should clear a datetime-local input", function () { + const $input = $(''); + + $input.clearFields(); + + assert.strictEqual($input.val(), ""); + }); + + it("should empty a textarea", function () { + const $textarea = $(""); + + $textarea.clearFields(); + + assert.strictEqual($textarea.val(), ""); + }); + + it("should deselect every option when a multiple select is cleared", function () { + const $select = $( + "" + ); + + $select.clearFields(); + + assert.strictEqual($select[0].selectedIndex, -1); + assert.deepEqual($select.val(), Number($.fn.jquery.split(".")[0]) < 3 ? null : []); + }); + + it("should clear a selected file when the user agent is not MSIE", function () { + const input = $('')[0]; + selectFiles(input, ["a.txt"]); + + $(input).clearFields(); + + assert.strictEqual(input.files.length, 0); + }); + + it("should carry data and handlers to the replacement and return the old element when simulating MSIE", function () { + const $container = $('
'); + const $file = $container.find("input"); + let handled = 0; + $file.data("key", "kept"); + $file.on("custom", () => handled++); + + const result = withUserAgent("MSIE 10.0", () => $file.clearFields()); + + const $replacement = $container.find("input"); + $replacement.trigger("custom"); + assert.strictEqual(result[0], $file[0]); + assert.notStrictEqual($replacement[0], $file[0]); + assert.strictEqual($replacement.data("key"), "kept"); + assert.strictEqual(handled, 1); + }); + + it("should leave a detached file input unchanged when simulating MSIE", function () { + const input = $('')[0]; + selectFiles(input, ["a.txt"]); + + const result = withUserAgent("MSIE 10.0", () => $(input).clearFields()); + + assert.strictEqual(result[0], input); + assert.strictEqual(input.files.length, 1); + }); + + const buttonsAndHidden = + '
' + + '
'; + + function fieldValues($fields) { + return $fields + .map(function () { + return this.value; + }) + .get(); + } + + [ + ["undefined", undefined], + ["false", false], + ["0", 0], + ["an empty string", ""], + ["null", null], + ].forEach(function ([label, includeHidden]) { + it( + "should leave hidden and button inputs and button elements unchanged when includeHidden is " + + label, + function () { + const $fields = $(buttonsAndHidden).find("input,button"); + + $fields.clearFields(includeHidden); + + assert.deepEqual(fieldValues($fields), ["h", "b", "r", "i", "s", "bb"]); + } + ); + }); + + it("should clear only hidden inputs when includeHidden is true", function () { + const $fields = $(buttonsAndHidden).find("input,button"); + + $fields.clearFields(true); + + assert.deepEqual(fieldValues($fields), ["", "b", "r", "i", "s", "bb"]); + }); + + it("should clear a submit input and a button that match an includeHidden selector", function () { + const $fields = $(buttonsAndHidden).find("input,button"); + $fields.filter("[type=submit],button").addClass("special"); + + $fields.clearFields(".special"); + + assert.deepEqual(fieldValues($fields), ["h", "b", "r", "i", "", ""]); + }); + + [ + ["a number", () => 1], + ["an object", () => ({})], + ["an element", () => document.createElement("input")], + ["a jQuery set", () => $('')], + ].forEach(function ([label, makeValue]) { + it("should ignore includeHidden when it is " + label, function () { + const $hidden = $(''); + const includeHidden = makeValue(); + + $hidden.clearFields(includeHidden); + + assert.strictEqual($hidden.val(), "h"); + }); + }); + + it("should throw a selector syntax error on jQuery 3 and later when includeHidden is not a valid selector", function () { + const $hidden = $(''); + + const clear = () => $hidden.clearFields("["); + + if (Number($.fn.jquery.split(".")[0]) < 3) { + assert.doesNotThrow(clear); + } else { + assert.throws(clear, /unrecognized expression/); + } + }); + + it("should set a value expando on a non-control that matches the includeHidden selector", function () { + const div = $("
")[0]; + + $(div).clearFields("div"); + + assert.strictEqual(div.value, ""); + }); + + it("should not fire change or input events when clearing", function () { + const $container = $( + '
' + ).appendTo("#main"); + + const events = recordFieldEvents($container[0], () => $container.clearForm()); + + assert.deepEqual(events, []); + assert.strictEqual($container.find("textarea").val(), ""); + }); + + it("should clear disabled and readonly fields", function () { + const $fields = $('
').find( + "input" + ); + + $fields.clearFields(); + + assert.deepEqual(fieldValues($fields), ["", ""]); + }); + }); + + describe("enable and selected", function () { + // #600: the document and text nodes have no tag name. + it("should skip nodes without a tag name when selecting", function () { + const $nodes = $([document, document.createTextNode("text")]); + + const select = () => $nodes.selected(); + + assert.doesNotThrow(select); + }); + + it("should leave controls that cannot be selected unchanged", function () { + const input = $('')[0]; + + $(input).selected(true); + + assert.strictEqual(input.checked, false); + assert.strictEqual(input.selected, undefined); + }); + + it("should enable by default and disable when passed false", function () { + const $input = $(""); + + const enabled = $input.enable(); + const isEnabled = !$input.prop("disabled"); + const disabled = $input.enable(false); + + assert.strictEqual(enabled, $input); + assert.strictEqual(isEnabled, true); + assert.strictEqual(disabled, $input); + assert.strictEqual($input.prop("disabled"), true); + }); + + it("should check and uncheck checkbox and radio controls", function () { + const $controls = $('
').find("input"); + + $controls.selected(); + const selected = $controls + .map(function () { + return this.checked; + }) + .get(); + $controls.selected(false); + + assert.deepEqual(selected, [true, true]); + assert.deepEqual( + $controls + .map(function () { + return this.checked; + }) + .get(), + [false, false] + ); + }); + + it("should select one option while deselecting its single-select siblings", function () { + const $select = $(""); + const $options = $select.find("option"); + + const result = $options.eq(1).selected(); + + assert.strictEqual(result[0], $options[1]); + assert.strictEqual($options.eq(0).prop("selected"), false); + assert.strictEqual($options.eq(1).prop("selected"), true); + }); + + it("should independently select options in a multiple select", function () { + const $options = $( + "" + ).find("option"); + + $options.eq(1).selected(); + + assert.deepEqual( + $options + .map(function () { + return this.selected; + }) + .get(), + [true, true] + ); + }); + + it("should disable for null, 0 and an empty string, and enable for the string false and 1", function () { + const $input = $(""); + + const disabled = [null, 0, "", "false", 1].map(function (value) { + $input.enable(value); + return $input[0].disabled; + }); + + assert.deepEqual(disabled, [true, true, true, false, false]); + }); + + it("should toggle the disabled attribute on controls and only set an expando on a div", function () { + const $controls = $( + "
" + ).find("input,fieldset,optgroup,option"); + const $div = $("
"); + + $controls.add($div).enable(false); + const added = $controls + .map(function () { + return this.hasAttribute("disabled"); + }) + .get(); + $controls.enable(); + + assert.deepEqual(added, [true, true, true, true]); + assert.strictEqual($controls.filter("[disabled]").length, 0); + assert.strictEqual($div[0].disabled, true); + assert.isFalse($div[0].hasAttribute("disabled")); + }); + + it("should not fire events when enabling or disabling", function () { + const $container = $("
").appendTo("#main"); + + const events = recordFieldEvents($container[0], function () { + $container.find("input").enable(false).enable(); + }); + + assert.deepEqual(events, []); + }); + + it("should return the original set when selecting", function () { + const $checkbox = $(''); + + const result = $checkbox.selected(); + + assert.strictEqual(result, $checkbox); + }); + + it("should check a checkbox when passed the string false and uncheck it for 0 and null", function () { + const $checkbox = $(''); + + const checked = ["false", 0, "x", null].map(function (value) { + $checkbox.selected(value); + return $checkbox[0].checked; + }); + + assert.deepEqual(checked, [true, false, true, false]); + }); + + it("should leave the last radio of a group checked when several are selected", function () { + const $radios = $( + '
' + ) + .appendTo("#main") + .find("input"); + + $radios.selected(); + + assert.deepEqual( + $radios + .map(function () { + return this.checked; + }) + .get(), + [false, true] + ); + }); + + it("should leave only the chosen option selected when it is inside an optgroup of a single select", function () { + const $options = $( + "" + ).find("option"); + + $options.eq(1).selected(); + + assert.deepEqual(selectedStates($options), [false, true]); + }); + + it("should fall back to the first option when the selected option of a dropdown is deselected", function () { + const $options = $("").find( + "option" + ); + + $options.eq(1).selected(false); + const afterSecond = selectedStates($options); + $options.eq(0).selected(false); + + assert.deepEqual(afterSecond, [true, false]); + assert.deepEqual(selectedStates($options), [true, false]); + }); + + it("should set selected on an option that has no parent select", function () { + const option = $('').find("option")[0]; + + $(option).selected(); + + assert.strictEqual(option.selected, true); + }); + + it("should not fire change events when selecting", function () { + const $container = $( + '
' + ).appendTo("#main"); + + const events = recordFieldEvents($container[0], function () { + $container.find("input").selected(); + $container.find("option").eq(1).selected(); + }); + + assert.deepEqual(events, []); + }); + }); +}); diff --git a/test/suite/form-members.test.js b/test/suite/form-members.test.js new file mode 100644 index 0000000..03c34a0 --- /dev/null +++ b/test/suite/form-members.test.js @@ -0,0 +1,78 @@ +import { assert, describe, it } from "vitest"; +import { callFormMethod, formMember } from "../../src/form-members.js"; + +describe("form members", function () { + describe("formMember", function () { + it("should read the prototype value when a control shadows the member", function () { + const form = $('
')[0]; + + const elements = formMember(form, "elements"); + + assert.strictEqual(elements.length, 2); + }); + + it("should read a member inherited from a prototype further up the chain", function () { + const form = $('
')[0]; + + const ownerDocument = formMember(form, "ownerDocument"); + + assert.strictEqual(ownerDocument, document); + }); + + it("should read the plain property when the getter does not accept the element", function () { + const fieldset = $('
')[0]; + + const elements = formMember(fieldset, "elements"); + + assert.strictEqual(elements, fieldset.elements); + }); + + it("should read the plain property when no prototype has the member", function () { + const form = $('
')[0]; + const HTMLFormElement = window.HTMLFormElement; + window.HTMLFormElement = undefined; + let elements; + + try { + elements = formMember(form, "elements"); + } finally { + window.HTMLFormElement = HTMLFormElement; + } + + assert.strictEqual(elements, form.querySelector("input")); + }); + }); + + describe("callFormMethod", function () { + it("should call the prototype method when a control shadows it", function () { + const form = $('
')[0]; + + callFormMethod(form, "setAttribute", "action", "ajax/text.html"); + + assert.strictEqual(form.getAttribute("action"), "ajax/text.html"); + }); + + it("should return the method's result", function () { + const form = $('
')[0]; + + const id = callFormMethod(form, "getAttribute", "id"); + + assert.strictEqual(id, "members"); + }); + + it("should call the method of an unshadowed form when no prototype has it", function () { + const form = $('
')[0]; + const HTMLFormElement = window.HTMLFormElement; + window.HTMLFormElement = undefined; + let valid; + + try { + valid = callFormMethod(form, "checkValidity"); + } finally { + window.HTMLFormElement = HTMLFormElement; + } + + assert.strictEqual(valid, false); + }); + }); +}); diff --git a/test/suite/helpers.js b/test/suite/helpers.js new file mode 100644 index 0000000..f3ca0e3 --- /dev/null +++ b/test/suite/helpers.js @@ -0,0 +1,250 @@ +import { afterEach, beforeAll, beforeEach } from "vitest"; +import { resetDeprecations } from "../../src/diagnostics.js"; + +// helper method +export var arrayCount = function (arr, key) { + var count = 0; + for (var i = 0; i < arr.length; i++) { + if (arr[i].name === key) { + count++; + } + } + return count; +}; + +// helper method +export var arrayValue = function (arr, key) { + for (var i = 0; i < arr.length; i++) { + if (arr[i].name === key) { + return arr[i].value; + } + } + return undefined; +}; + +// Selects new text files named `names` in a file input and returns them. +export function selectFiles(input, names) { + const transfer = new DataTransfer(); + names.forEach(function (name) { + transfer.items.add(new File(["contents of " + name], name, { type: "text/plain" })); + }); + input.files = transfer.files; + + return Array.prototype.slice.call(input.files); +} + +var fixture; + +// Restores the #main fixture before each test. +export function resetFixture() { + beforeAll(function () { + fixture = $("#main").html(); + }); + + beforeEach(function () { + $("#main").html(fixture); + }); +} + +// Starts a submit via `trigger` (which must use `opts`) and resolves once the request settles. +// Resolves with what the callbacks saw, so the test can assert on it after the awaited act. +export function submitAndSettle(opts, trigger) { + const seen = { beforeSubmit: null, success: null, error: null }; + + return new Promise(function (resolve) { + const userBeforeSubmit = opts.beforeSubmit; + opts.beforeSubmit = function (data, $form) { + seen.beforeSubmit = { data: data, $form: $form }; + return userBeforeSubmit ? userBeforeSubmit.apply(this, arguments) : undefined; + }; + opts.success = function () { + seen.success = Array.prototype.slice.call(arguments); + resolve(seen); + }; + opts.error = function () { + seen.error = Array.prototype.slice.call(arguments); + resolve(seen); + }; + trigger(); + }); +} + +// Submits through a stubbed $.ajax and returns the settings it received. +export function captureAjaxOptions($form, options, respond) { + const ajax = $.ajax; + let settings; + $.ajax = function (received) { + settings = received; + if (respond) { + respond(received); + } + return {}; + }; + + try { + $form.ajaxSubmit(options); + } finally { + $.ajax = ajax; + } + + return settings; +} + +export function withUserAgent(userAgent, run) { + Object.defineProperty(navigator, "userAgent", { configurable: true, value: userAgent }); + + try { + return run(); + } finally { + delete navigator.userAgent; + } +} + +export function withDocumentUrl(url, run) { + Object.defineProperty(document, "URL", { configurable: true, value: url }); + + try { + return run(); + } finally { + delete document.URL; + } +} + +export async function withAjaxStub(stub, run) { + const ajax = $.ajax; + $.ajax = stub; + + try { + return await run(); + } finally { + $.ajax = ajax; + } +} + +// Runs `run` with `overrides` merged into $.ajaxSettings, then restores each key (or removes it). +export async function withAjaxSettings(overrides, run) { + const saved = {}; + Object.keys(overrides).forEach(function (key) { + saved[key] = Object.prototype.hasOwnProperty.call($.ajaxSettings, key) + ? { value: $.ajaxSettings[key] } + : null; + $.ajaxSettings[key] = overrides[key]; + }); + + try { + return await run(); + } finally { + Object.keys(saved).forEach(function (key) { + if (saved[key]) { + $.ajaxSettings[key] = saved[key].value; + } else { + delete $.ajaxSettings[key]; + } + }); + } +} + +// Submits through a stubbed $.ajax and names the transport ajaxSubmit chose: "formdata" or +// "plain" for the $.ajax paths, "iframe" when the plugin itself calls beforeSend (vetoed here, so +// nothing is posted), or "none". Returns { transport, settings }. +export function submitTransport($form, options) { + const ajax = $.ajax; + const result = { transport: "none", settings: undefined }; + $.ajax = function (settings) { + result.settings = settings; + result.transport = + settings.contentType === false && settings.processData === false ? "formdata" : "plain"; + return {}; + }; + + try { + $form.ajaxSubmit( + $.extend({ global: false }, options, { + beforeSend: function () { + result.transport = "iframe"; + return false; + }, + }) + ); + } finally { + $.ajax = ajax; + } + + return result; +} + +// Builds a form without jQuery's HTML parsing, which calls getElementsByTagName on the form and +// so cannot build one whose control shadows that method. +export function buildForm(innerHtml, action) { + const form = document.createElement("form"); + form.innerHTML = innerHtml; + if (action) { + form.setAttribute("action", action); + } + + return form; +} + +// Builds a form whose control named parentNode hides the form's parentNode, without passing it +// through jQuery: jQuery's own parentNode walks would cycle between the form and the control. +export function formHidingParentNode(innerHtml) { + const form = document.createElement("form"); + form.innerHTML = '' + (innerHtml || ""); + + return form; +} + +// Restores $.active and removes generated upload frames after each test, since some iframe exit +// paths never settle and would leak into the next test. +export function restoreAjaxState() { + let active; + + beforeEach(function () { + active = $.active; + }); + + afterEach(function () { + $.active = active; + $("iframe[name^=jqFormIO]").remove(); + }); +} + +// Runs `run` while recording uncaught window errors instead of failing the run with them. Resolves +// with what `run` returned; the errors array is passed to `run` so it can assert on them. +export async function withWindowErrors(run) { + const errors = []; + const record = function (event) { + event.preventDefault(); + errors.push(event.error); + }; + window.addEventListener("error", record); + + try { + return await run(errors); + } finally { + window.removeEventListener("error", record); + } +} + +// Runs `run` with debug set as given and console.warn recorded; returns the warnings. The +// once-per-page record of deprecations is cleared before and after. +export function recordDeprecations(debug, run) { + const warnings = []; + const warn = console.warn; + const log = console.log; + console.warn = (text) => warnings.push(text); + console.log = () => {}; + resetDeprecations(); + $.fn.ajaxSubmit.debug = debug; + + try { + run(); + } finally { + $.fn.ajaxSubmit.debug = false; + console.warn = warn; + console.log = log; + resetDeprecations(); + } + + return warnings; +} diff --git a/test/suite/iframe-response.test.js b/test/suite/iframe-response.test.js new file mode 100644 index 0000000..b46c632 --- /dev/null +++ b/test/suite/iframe-response.test.js @@ -0,0 +1,112 @@ +import { assert, describe, it } from "vitest"; +import { getDoc, httpData, readResponse } from "../../src/iframe-response.js"; + +describe("iframe response reader", function () { + function parse(markup, type) { + return new DOMParser().parseFromString(markup, type || "text/html"); + } + + function mockXhr() { + return { status: 0, statusText: "n/a", responseText: null, responseXML: null }; + } + + function noRetry() { + return false; + } + + describe("getDoc", function () { + it("should return the content window's document", function () { + const doc = parse("

hi

"); + + const result = getDoc({ contentWindow: { document: doc } }); + + assert.strictEqual(result, doc); + }); + + it("should fall back to contentDocument without a content window", function () { + const doc = parse("

hi

"); + + const result = getDoc({ contentDocument: doc }); + + assert.strictEqual(result, doc); + }); + }); + + describe("readResponse", function () { + it("should read the body markup and the emulated status of an HTML document", function () { + const doc = parse('ok'); + const xhr = mockXhr(); + + const result = readResponse(doc, xhr, {}, noRetry); + + assert.deepEqual(result, { status: "success", data: "ok", errMsg: undefined }); + assert.strictEqual(xhr.status, 201); + assert.strictEqual(xhr.statusText, "Created"); + assert.strictEqual(xhr.responseXML, doc); + }); + + it("should detect an XML document and return it as the data", function () { + const doc = parse("1", "application/xml"); + const xhr = mockXhr(); + const s = {}; + + const result = readResponse(doc, xhr, s, noRetry); + + assert.strictEqual(result.data, doc); + assert.strictEqual(s.dataType, "xml"); + assert.strictEqual(xhr.getResponseHeader("Content-Type"), "xml"); + }); + + it("should parse JSON embedded in a textarea", function () { + const doc = parse(''); + const xhr = mockXhr(); + + const result = readResponse(doc, xhr, { dataType: "json" }, noRetry); + + assert.strictEqual(xhr.responseText, '{"a":1}'); + assert.strictEqual(xhr.status, 202); + assert.strictEqual(result.status, "success"); + }); + + it("should read JSON text wrapped in a pre element", function () { + const doc = parse('
{"a":1}
'); + const xhr = mockXhr(); + + readResponse(doc, xhr, { dataType: "json" }, noRetry); + + assert.strictEqual(xhr.responseText, '{"a":1}'); + }); + + it("should report a parsererror when dataFilter throws", function () { + const doc = parse("

x

"); + const xhr = mockXhr(); + const failure = new Error("bad"); + const s = { + dataFilter: function () { + throw failure; + }, + }; + + const result = readResponse(doc, xhr, s, noRetry); + + assert.strictEqual(result.status, "parsererror"); + assert.strictEqual(result.errMsg, failure); + assert.strictEqual(xhr.error, failure); + }); + }); + + describe("httpData", function () { + it("should parse JSON text when no dataType is given and the content type is json", function () { + const xhr = { + responseText: '{"a":1}', + getResponseHeader: function () { + return "application/json"; + }, + }; + + const data = httpData(xhr, "", null); + + assert.deepEqual(data, { a: 1 }); + }); + }); +}); diff --git a/test/suite/iframe-transport.test.js b/test/suite/iframe-transport.test.js new file mode 100644 index 0000000..9442e5f --- /dev/null +++ b/test/suite/iframe-transport.test.js @@ -0,0 +1,3099 @@ +import { afterEach, assert, describe, it, vi } from "vitest"; +import { + recordDeprecations, + resetFixture, + restoreAjaxState, + selectFiles, + submitTransport, + withAjaxSettings, + withWindowErrors, +} from "./helpers.js"; + +describe("form", function () { + resetFixture(); + + describe("ajaxSubmit", function () { + describe("iframe upload transport", function () { + restoreAjaxState(); + + function createIframeForm(action) { + return $('
') + .attr("action", action) + .appendTo("#main"); + } + + function submitThroughIframe($form, options) { + return new Promise(function (resolve) { + const result = { events: [] }; + const settings = $.extend({}, options, { + iframe: true, + success: function () { + result.success = Array.from(arguments); + result.events.push("success"); + }, + error: function () { + result.error = Array.from(arguments); + result.events.push("error"); + }, + complete: function () { + result.complete = Array.from(arguments); + result.events.push("complete"); + resolve(result); + }, + }); + + $form.ajaxSubmit(settings); + result.xhr = $form.data("jqxhr"); + }); + } + + function inspectNativeSubmit($form, inspect) { + const form = $form[0]; + const nativeSubmit = form.submit; + form.submit = function () { + inspect(form); + delete form.submit; + nativeSubmit.call(form); + }; + } + + it("should submit through a generated iframe and clean it up", async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + const initialFrames = $("iframe").length; + + const result = await submitThroughIframe($form, { forceSync: true, dataType: "text" }); + await new Promise((resolve) => setTimeout(resolve, 150)); + + assert.strictEqual(result.success[0].trim(), "iframe response"); + assert.strictEqual(result.success[1], "success"); + assert.strictEqual(result.success[2].status, 201); + assert.deepEqual(result.events, ["success", "complete"]); + assert.strictEqual($("iframe").length, initialFrames); + }); + + it("should use and reset a supplied iframe target", async function () { + const $target = $('').appendTo("#main"); + const $form = createIframeForm("ajax/iframe-text.html"); + + const result = await submitThroughIframe($form, { + iframeTarget: $target, + dataType: "text", + }); + await new Promise((resolve) => setTimeout(resolve, 150)); + + assert.strictEqual(result.success[0].trim(), "iframe response"); + assert.strictEqual($target.attr("name"), "provided-frame"); + assert.strictEqual($target.attr("src"), "about:blank"); + assert.strictEqual($target.parent().length, 1); + }); + + it("should name a supplied iframe target that has no name", function () { + const $target = $("").appendTo("#main"); + const $form = createIframeForm("ajax/iframe-text.html"); + + $form.ajaxSubmit({ + iframe: true, + iframeTarget: $target, + beforeSend: function () { + return false; + }, + }); + + assert.match($target.attr("name"), /^jqFormIO\d+$/); + }); + + it("should reject when beforeSend aborts the iframe request", async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + let xhr; + + $form.ajaxSubmit({ + iframe: true, + beforeSend: function (request) { + xhr = request; + request.abort("early"); + }, + }); + const deferred = $form.data("jqxhr"); + const rejected = await new Promise((resolve) => deferred.fail(() => resolve(true))); + + assert.strictEqual(rejected, true); + assert.strictEqual(xhr.error, "aborted"); + assert.strictEqual(xhr.aborted, 1); + }); + + it("should submit clicked image values and coordinates as hidden inputs", async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + const image = $('').appendTo($form)[0]; + const submitted = {}; + $form[0].clk = image; + $form[0].clk_x = 12; + $form[0].clk_y = 34; + inspectNativeSubmit($form, function (form) { + $(form) + .find('input[type="hidden"]') + .each(function () { + submitted[this.name] = this.value; + }); + }); + + await submitThroughIframe($form, { dataType: "text" }); + + assert.deepEqual(submitted, { map: "go", "map.x": "12", "map.y": "34" }); + }); + + it("should submit CSRF metadata and remove its temporary input", async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + const $token = $('').appendTo(document.head); + const $param = $('').appendTo( + document.head + ); + let submittedToken; + inspectNativeSubmit($form, function (form) { + submittedToken = $(form).find('[name="authenticity_token"]').val(); + }); + + try { + await submitThroughIframe($form, { dataType: "text" }); + + assert.strictEqual(submittedToken, "secret"); + assert.strictEqual($form.find('[name="authenticity_token"]').length, 0); + } finally { + $token.remove(); + $param.remove(); + } + }); + + it("should not send CSRF metadata to another origin", function () { + const $form = createIframeForm("https://upload.example.invalid/form"); + const $token = $('').appendTo(document.head); + const $param = $('').appendTo( + document.head + ); + let submittedTokens; + $form[0].submit = function () { + submittedTokens = $(this).find('[name="authenticity_token"]').length; + }; + + try { + $form.ajaxSubmit({ iframe: true, forceSync: true, error: function () {} }); + $form.data("jqxhr").abort(); + + assert.strictEqual(submittedTokens, 0); + } finally { + $token.remove(); + $param.remove(); + } + }); + + for (const [label, markup] of [ + ["a get form", '
'], + ["a form without a method", ""], + ]) { + it(`should not send CSRF metadata with ${label}, whose query it would join`, function () { + const $form = $(markup + '
') + .attr("action", "ajax/iframe-text.html") + .appendTo("#main"); + const $token = $('').appendTo(document.head); + const $param = $('').appendTo( + document.head + ); + let submittedTokens; + $form[0].submit = function () { + submittedTokens = $(this).find('[name="authenticity_token"]').length; + }; + + try { + $form.ajaxSubmit({ iframe: true, forceSync: true, error: function () {} }); + $form.data("jqxhr").abort(); + + assert.strictEqual(submittedTokens, 0); + } finally { + $token.remove(); + $param.remove(); + } + }); + } + + for (const [type, method, tokens] of [ + ["GET", "get", 0], + ["PUT", "post", 1], + ]) { + it(`should submit a post form with ${method} and ${tokens} CSRF field when the type option is ${type}`, function () { + const $form = createIframeForm("ajax/iframe-text.html"); + const $metas = $( + '' + ).appendTo(document.head); + let submitted; + $form[0].submit = function () { + submitted = [this.method, $(this).find('[name="authenticity_token"]').length]; + }; + + try { + $form.ajaxSubmit({ iframe: true, forceSync: true, type: type, error: function () {} }); + $form.data("jqxhr").abort(); + + assert.deepEqual(submitted, [method, tokens]); + } finally { + $metas.remove(); + } + }); + } + + it("should override the action during submission and then restore it", async function () { + const $form = createIframeForm("ajax/original.html"); + let submittedAction; + inspectNativeSubmit($form, function (form) { + submittedAction = form.getAttribute("action"); + }); + + await submitThroughIframe($form, { url: "ajax/iframe-text.html", dataType: "text" }); + + assert.ok(submittedAction.endsWith("ajax/iframe-text.html")); + assert.ok($form.attr("action").endsWith("ajax/original.html")); + }); + + it("should submit both extraData representations and remove temporary inputs", async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + const submitted = {}; + inspectNativeSubmit($form, function (form) { + $(form) + .find('input[type="hidden"]') + .each(function () { + submitted[this.name] = this.value; + }); + }); + + await submitThroughIframe($form, { + data: { + plain: "value", + aliased: { name: "actual", value: "represented" }, + }, + dataType: "text", + }); + + assert.deepEqual(submitted, { plain: "value", actual: "represented" }); + assert.strictEqual($form.find('input[type="hidden"]').length, 0); + }); + + it("should fall back to native submission when a control shadows form.submit", async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + $('').appendTo($form); + + const result = await submitThroughIframe($form, { dataType: "text" }); + + assert.strictEqual(result.success[0].trim(), "iframe response"); + }); + + it("should restore an original form target after submission", async function () { + const $form = createIframeForm("ajax/iframe-text.html").attr("target", "original-target"); + + await submitThroughIframe($form, { dataType: "text" }); + + assert.strictEqual($form.attr("target"), "original-target"); + }); + + it("should wait for closeKeepAlive before creating the iframe request", async function () { + const originalGet = $.get; + const $form = createIframeForm("ajax/iframe-text.html"); + let release; + let resolveCompletion; + const completed = new Promise((resolve) => { + resolveCompletion = resolve; + }); + $.get = function (_url, callback) { + release = callback; + }; + + try { + $form.ajaxSubmit({ + iframe: true, + closeKeepAlive: "/close", + dataType: "text", + complete: resolveCompletion, + }); + const beforeRelease = $form.data("jqxhr"); + + release(); + await completed; + + assert.strictEqual(beforeRelease, undefined); + } finally { + $.get = originalGet; + } + }); + + it("should insert what dataFilter returns into the target on an upload", async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + const $target = $('
kept
').appendTo("#main"); + + await submitThroughIframe($form, { + target: $target, + dataFilter: (data) => "filtered " + typeof data, + }); + + assert.strictEqual($target.text(), "filtered string"); + }); + + it("should parse textarea JSON and apply dataFilter", async function () { + const $form = createIframeForm("ajax/iframe-json.html"); + let filtered; + + const result = await submitThroughIframe($form, { + dataType: "json", + textarea: true, + dataFilter: function (data, type) { + filtered = [data, type]; + return data; + }, + }); + + assert.deepEqual(result.success[0], { transport: "iframe" }); + assert.deepEqual(filtered, ['{"transport":"iframe"}', "json"]); + assert.strictEqual(result.success[2].status, 202); + assert.strictEqual(result.success[2].statusText, "accepted"); + }); + + it("should evaluate script from a pre response", async function () { + const $form = createIframeForm("ajax/iframe-script.html"); + delete window.iframeTransportScript; + + const result = await submitThroughIframe($form, { dataType: "script" }); + + assert.strictEqual(window.iframeTransportScript, "evaluated"); + assert.ok(result.success[0].includes("iframeTransportScript")); + delete window.iframeTransportScript; + }); + + it("should return an XML document", async function () { + const $form = createIframeForm("ajax/iframe-xml.html"); + + const result = await submitThroughIframe($form, { dataType: "xml" }); + + assert.strictEqual(result.success[0].documentElement.nodeName, "response"); + assert.strictEqual( + result.success[0].getElementsByTagName("transport")[0].textContent, + "iframe" + ); + }); + + it("should expose the iframe mock response header methods", async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + + const result = await submitThroughIframe($form, { dataType: "text" }); + const xhr = result.success[2]; + + assert.strictEqual(xhr.getResponseHeader("Content-Type"), "text"); + assert.strictEqual(xhr.getResponseHeader("Missing"), undefined); + assert.strictEqual(xhr.getAllResponseHeaders(), undefined); + assert.strictEqual(xhr.setRequestHeader("X-Test", "ignored"), undefined); + }); + + it("should clear a pending timeout after a successful response", async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + + const result = await submitThroughIframe($form, { dataType: "text", timeout: 1000 }); + await new Promise((resolve) => setTimeout(resolve, 20)); + + assert.deepEqual(result.events, ["success", "complete"]); + assert.strictEqual(result.xhr.error, undefined); + }); + + it("should report emulated HTTP errors and complete once", async function () { + const $form = createIframeForm("ajax/iframe-error.html"); + + const result = await submitThroughIframe($form, { dataType: "text" }); + + assert.strictEqual(result.error[0].status, 500); + assert.strictEqual(result.error[1], "error"); + assert.strictEqual(result.error[2], "fixture failure"); + assert.deepEqual(result.events, ["error", "complete"]); + }); + + it("should report an emulated HTTP error before a parser error", async function () { + const $form = createIframeForm("ajax/iframe-error.html"); + + const result = await submitThroughIframe($form, { dataType: "json" }); + + assert.strictEqual(result.error[1], "error"); + assert.deepEqual(result.events, ["error", "complete"]); + }); + + it("should report malformed JSON as a parser error despite a success status", async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + + const result = await submitThroughIframe($form, { dataType: "json" }); + + assert.strictEqual(result.error[1], "parsererror"); + assert.ok(result.error[2] instanceof Error); + }); + + it("should honor a beforeSend veto without submitting or completing", async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + let complete = false; + + $form.ajaxSubmit({ + iframe: true, + beforeSend: function () { + return false; + }, + complete: function () { + complete = true; + }, + }); + const xhr = $form.data("jqxhr"); + const rejected = await new Promise((resolve) => xhr.fail(() => resolve(true))); + + assert.strictEqual(rejected, true); + assert.strictEqual(complete, false); + }); + + it("should time out an iframe request and call error then complete", async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + + const result = await submitThroughIframe($form, { timeout: 1 }); + + assert.strictEqual(result.error[1], "timeout"); + assert.strictEqual(result.complete[1], "timeout"); + assert.deepEqual(result.events, ["error", "complete"]); + }); + + it("should emit matching global lifecycle events", async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + const events = []; + const names = "ajaxStart ajaxSend ajaxSuccess ajaxComplete ajaxStop"; + const active = $.active; + $.active = 0; + $(document).on(names, function (event) { + events.push(event.type); + }); + + try { + await submitThroughIframe($form, { dataType: "text", global: true }); + + assert.deepEqual(events, names.split(" ")); + assert.strictEqual($.active, 0); + } finally { + $(document).off(names); + $.active = active; + } + }); + + it("should abort from beforeSend without global events", async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + const events = []; + $(document).on("ajaxSend ajaxError", (event) => events.push(event.type)); + + try { + $form.ajaxSubmit({ + iframe: true, + global: false, + beforeSend: (request) => request.abort(), + }); + const state = await new Promise((resolve) => + $form.data("jqxhr").fail(() => resolve("rejected")) + ); + + assert.strictEqual(state, "rejected"); + assert.deepEqual(events, []); + } finally { + $(document).off("ajaxSend ajaxError"); + } + }); + + it("should leave the active count alone when beforeSend vetoes without global events", function () { + const $form = createIframeForm("ajax/iframe-text.html"); + const active = $.active; + + $form.ajaxSubmit({ iframe: true, global: false, beforeSend: () => false }); + + assert.strictEqual($.active, active); + assert.strictEqual($form.data("jqxhr").state(), "rejected"); + }); + + [ + ["an unnamed clicked button", '', {}], + [ + "a named clicked submit button", + '', + { choice: "picked" }, + ], + ].forEach(function ([label, markup, expected]) { + it("should submit hidden values for " + label, async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + $form[0].clk = $(markup).appendTo($form)[0]; + const submitted = {}; + inspectNativeSubmit($form, function (form) { + $(form) + .find('input[type="hidden"]') + .each(function () { + submitted[this.name] = this.value; + }); + }); + + await submitThroughIframe($form, { dataType: "text" }); + + assert.deepEqual(submitted, expected); + }); + }); + + it("should keep GET method and encoding when submitting with GET", async function () { + const $form = createIframeForm("ajax/iframe-text.html").attr("method", "get"); + let submitted; + inspectNativeSubmit($form, function (form) { + submitted = [form.getAttribute("method"), form.getAttribute("enctype")]; + }); + + const result = await submitThroughIframe($form, { dataType: "text" }); + + assert.deepEqual(submitted, ["get", null]); + assert.strictEqual(result.success[0].trim(), "iframe response"); + }); + + // #597: arrays and objects are sent as $.param sends them. + it("should submit array extraData values as separate fields", async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + const submitted = []; + inspectNativeSubmit($form, function (form) { + $(form) + .find('input[type="hidden"]') + .each(function () { + submitted.push([this.name, this.value]); + }); + }); + + await submitThroughIframe($form, { data: { tags: ["a", "b"] }, dataType: "text" }); + + assert.deepEqual(submitted, [ + ["tags[]", "a"], + ["tags[]", "b"], + ]); + }); + + it("should submit nested extraData objects as bracketed fields", async function () { + const $form = createIframeForm("ajax/iframe-text.html"); + const submitted = []; + inspectNativeSubmit($form, function (form) { + $(form) + .find('input[type="hidden"]') + .each(function () { + submitted.push([this.name, this.value]); + }); + }); + + await submitThroughIframe($form, { + data: { meta: { owner: "Ada", tags: ["x"] }, plain: "a+b c" }, + dataType: "text", + }); + + assert.deepEqual(submitted, [ + ["meta[owner]", "Ada"], + ["meta[tags][]", "x"], + ["plain", "a+b c"], + ]); + }); + + // Starts an iframe upload whose native submit only records the generated hidden inputs and + // iframe, then aborts it. + async function submitAndAbort($form, options) { + const seen = {}; + $form[0].submit = function () { + seen.hidden = $(this) + .find('input[type="hidden"]') + .map(function () { + return [[this.name, this.value]]; + }) + .get(); + const target = this.getAttribute("target"); + seen.iframeSrc = $("iframe") + .filter((i, frame) => frame.name === target) + .attr("src"); + }; + + $form.ajaxSubmit($.extend({ iframe: true, forceSync: true, error: () => {} }, options)); + $form.data("jqxhr").abort(); + await new Promise((resolve) => setTimeout(resolve, 50)); + + return seen; + } + + const payload = '">'; + + [ + ["an extraData name", { extraData: { field: { name: payload, value: "v" } } }], + ["an extraData key", { extraData: { [payload]: "v" } }], + ].forEach(function ([label, options]) { + it("should submit " + label + " as text, not HTML", async function () { + window.iframePayload = 0; + const $form = createIframeForm("ajax/iframe-text.html"); + + const seen = await submitAndAbort($form, options); + + assert.deepEqual(seen.hidden, [[payload, "v"]]); + assert.strictEqual(window.iframePayload, 0); + }); + }); + + it("should submit a clicked button's name as text, not HTML", async function () { + window.iframePayload = 0; + const $form = createIframeForm("ajax/iframe-text.html"); + const $button = $('' + ); + + const plain = $form.formToArray().map((field) => field.name); + const semantic = $form.formToArray(true).map((field) => field.name); + + assert.deepEqual(plain, ["a"]); + assert.deepEqual(semantic, ["a"]); + }); + + it('should send "on" for a checked checkbox without a value attribute', function () { + const $form = $('
'); + + const formData = $form.formToArray(); + + assert.deepEqual(formData, [{ name: "c", value: "on", type: "checkbox", required: false }]); + }); + + it("should include the clicked submit input at its position in both modes", function () { + const $form = $( + '
' + ); + $form[0].clk = $form.find('[type="submit"]')[0]; + + const plain = $form.formToArray(); + const semantic = $form.formToArray(true); + + const expected = [ + { name: "a", value: "1", type: "text", required: false }, + { name: "go", value: "Go", type: "submit", required: false }, + { name: "b", value: "2", type: "text", required: false }, + ]; + assert.deepEqual(plain, expected); + assert.deepEqual(semantic, expected); + }); + + it("should report required as undefined for a clicked button element", function () { + const $form = $('
'); + $form[0].clk = $form.find("button")[0]; + + const formData = $form.formToArray(); + + assert.deepEqual(formData, [ + { name: "go", value: "Go", type: "submit", required: undefined }, + ]); + }); + + it("should serialize a named submit button of a pseudo-form without a click", function () { + const $div = $( + '
' + ); + + const names = $div.formToArray().map((field) => field.name); + + assert.deepEqual(names, ["a", "go"]); + }); + + it("should not treat a submit button named clk as clicked", function () { + const $form = $( + '
' + ); + + const names = $form.formToArray().map((field) => field.name); + + assert.deepEqual(names, ["a"]); + }); + + it("should serialize unchanged when controls shadow other form members", function () { + const shadowed = [ + "submit", + "reset", + "ownerDocument", + "id", + "name", + "length", + "tagName", + "type", + "disabled", + "form", + ]; + + const results = shadowed.map((name) => + $(`
`) + .formToArray() + .map((field) => [field.name, field.value]) + ); + + assert.deepEqual( + results, + shadowed.map((name) => [ + ["a", "1"], + [name, "x"], + ]) + ); + }); + }); + + describe("controls named like form members", function () { + it("should serialize when a control named getAttribute shadows the form", function () { + const $form = $('
'); + + const formData = $form.formToArray(); + + assert.deepEqual( + formData.map((field) => [field.name, field.value]), + [["getAttribute", "x"]] + ); + }); + + it("should serialize semantically when a control named getElementsByTagName shadows the form", function () { + const $form = $(buildForm('')); + + const formData = $form.formToArray(true); + + assert.deepEqual( + formData.map((field) => field.name), + ["a", "getElementsByTagName"] + ); + }); + }); + + describe("image submitters", function () { + it("should skip every image input when semantic is true and nothing was clicked", function () { + const $form = $( + '
' + ); + + const names = $form.formToArray(true).map((field) => field.name); + + assert.deepEqual(names, ["a"]); + }); + + it("should skip images and keep the clicked button in place when semantic is true", function () { + const $form = $( + '
' + ); + $form[0].clk = $form.find("button")[0]; + + const names = $form.formToArray(true).map((field) => field.name); + + assert.deepEqual(names, ["go", "a"]); + }); + + it("should not append a clicked image that is disabled or unnamed when semantic is false", function () { + const $disabled = $( + '
' + ); + const $unnamed = $( + '
' + ); + $disabled[0].clk = $disabled.find('[type="image"]')[0]; + $unnamed[0].clk = $unnamed.find('[type="image"]')[0]; + + const disabledNames = $disabled.formToArray().map((field) => field.name); + const unnamedNames = $unnamed.formToArray().map((field) => field.name); + + assert.deepEqual(disabledNames, ["a"]); + assert.deepEqual(unnamedNames, ["a"]); + }); + + it("should append the clicked image when it is the only control and semantic is false", function () { + const $form = $('
'); + $form[0].clk = $form.find("input")[0]; + $form[0].clk_x = 4; + $form[0].clk_y = 6; + + const formData = $form.formToArray(); + + assert.deepEqual(formData, [ + { name: "map", value: "go" }, + { name: "map.x", value: 4 }, + { name: "map.y", value: 6 }, + ]); + }); + + it("should append a clicked image from outside the form when semantic is false", function () { + const $form = $('
'); + $form[0].clk = $('')[0]; + $form[0].clk_x = 1; + $form[0].clk_y = 2; + + const formData = $form.formToArray(); + + assert.deepEqual(formData, [ + { name: "a", value: "1", type: "text", required: false }, + { name: "far", value: "v" }, + { name: "far.x", value: 1 }, + { name: "far.y", value: 2 }, + ]); + }); + + it("should send an empty value for a clicked image without a value attribute", function () { + const $form = $('
'); + $form[0].clk = $form.find('[type="image"]')[0]; + + const plain = $form.formToArray(); + const semantic = $form.formToArray(true); + + assert.strictEqual(plain[1].value, ""); + assert.strictEqual(semantic[1].value, ""); + }); + + it("should leave the clicked image out of elements in both modes", function () { + const $form = $( + '
' + ); + $form[0].clk = $form.find('[type="image"]')[0]; + const plainElements = []; + const semanticElements = []; + + $form.formToArray(false, plainElements); + $form.formToArray(true, semanticElements); + + const text = $form.find('[name="a"]')[0]; + assert.deepEqual(plainElements, [text]); + assert.deepEqual(semanticElements, [text]); + }); + + it("should serialize missing click coordinates as empty values", function () { + const $form = $( + '
' + ); + $form[0].clk = $form.find('[type="image"]')[0]; + + const serialized = $form.formSerialize(); + + // jQuery before 3.0 turns undefined into "undefined" in $.param; later versions use "". + const missing = Number($.fn.jquery.split(".")[0]) < 3 ? "undefined" : ""; + assert.strictEqual(serialized, `a=1&map=go&map.x=${missing}&map.y=${missing}`); + }); + }); + + describe("values", function () { + it("should report the type and required state of scalar entries", function () { + const $form = $( + '
' + ); + + const formData = $form.formToArray(); + + assert.deepEqual(formData, [ + { name: "r", value: "1", type: "text", required: true }, + { name: "t", value: "x", type: "textarea", required: false }, + { name: "s", value: "o", type: "select-one", required: false }, + ]); + }); + + it("should return name and value only for multi-select entries, across optgroups", function () { + const $form = $( + '
' + ); + + const formData = $form.formToArray(); + + assert.deepEqual(formData, [ + { name: "m", value: "a" }, + { name: "m", value: "b" }, + ]); + }); + + it("should send the option at selectedIndex for a select-one", function () { + const $form = $( + '
' + ); + $form.find("select")[0].selectedIndex = 1; + + const formData = $form.formToArray(); + + assert.deepEqual(formData, [ + { name: "s", value: "y", type: "select-one", required: false }, + ]); + }); + + it("should omit a select-one whose selected placeholder option is disabled but list it in elements", function () { + const $form = $( + '
' + ); + const elements = []; + + const formData = $form.formToArray(false, elements); + + assert.deepEqual(formData, []); + assert.deepEqual(elements, [$form.find("select")[0]]); + }); + + it("should add a multi-select with only disabled selected options to elements without entries", function () { + const $form = $( + '
' + ); + const elements = []; + + const formData = $form.formToArray(false, elements); + + assert.deepEqual(formData, []); + assert.deepEqual(elements, [$form.find("select")[0]]); + }); + + it("should omit selects with no selected option and leave them out of elements", function () { + const $form = $( + '
' + ); + const elements = []; + + const formData = $form.formToArray(false, elements); + + assert.deepEqual(formData, []); + assert.deepEqual(elements, []); + }); + + it("should keep line feeds in option values unchanged", function () { + const $form = $('
'); + $form.find("option")[0].value = "a\nb"; + + const formData = $form.formToArray(); + + assert.strictEqual(formData[0].value, "a\nb"); + }); + + it("should normalize line endings of a textarea and of a hidden input", function () { + const $form = $( + '
' + ); + $form.find("textarea").val("a\nb"); + $form.find('[name="lf"]')[0].value = "c\nd"; + $form.find('[name="crlf"]')[0].value = "e\r\nf"; + + const values = $form.formToArray().map((field) => field.value); + + assert.deepEqual(values, ["a\r\nb", "c\r\nd", "e\r\nf"]); + }); + + it("should send a lone carriage return as CRLF on every jQuery version", function () { + const $form = $('
'); + $form.find("input")[0].value = "a\rb\r"; + + const formData = $form.formToArray(); + + assert.strictEqual(formData[0].value, "a\r\nb\r\n"); + }); + + it("should keep the value a jQuery valHook returns", function () { + const $form = $('
'); + const saved = $.valHooks.hidden; + $.valHooks.hidden = { + get: function () { + return "hooked"; + }, + }; + + try { + const formData = $form.formToArray(); + + assert.strictEqual(formData[0].value, "hooked"); + } finally { + if (saved) { + $.valHooks.hidden = saved; + } else { + delete $.valHooks.hidden; + } + } + }); + + it("should send the literal value of a hidden input named _charset_ and nothing for dirname", function () { + const $form = $( + '
' + ); + + const pairs = $form.formToArray().map((field) => [field.name, field.value]); + + assert.deepEqual(pairs, [ + ["_charset_", "literal"], + ["t", "v"], + ]); + }); + }); + + describe("file inputs", function () { + it("should return one File entry per selected file in FileList order", function () { + const $form = $('
'); + selectFiles($form.find("input")[0], ["one.txt", "two.txt"]); + + const formData = $form.formToArray(); + + assert.deepEqual( + formData.map((field) => [field.name, field.value instanceof File, field.value.name]), + [ + ["up", true, "one.txt"], + ["up", true, "two.txt"], + ] + ); + assert.deepEqual( + formData.map((field) => Object.keys(field)), + [ + ["name", "value", "type"], + ["name", "value", "type"], + ] + ); + }); + + it("should add a file input with selected files to elements once", function () { + const $form = $('
'); + const input = $form.find("input")[0]; + selectFiles(input, ["one.txt", "two.txt"]); + const elements = []; + + $form.formToArray(false, elements); + + assert.deepEqual(elements, [input]); + }); + + it("should skip a disabled or unnamed file input", function () { + const $form = $('
'); + selectFiles($form.find("input")[0], ["one.txt"]); + selectFiles($form.find("input")[1], ["two.txt"]); + const elements = []; + + const formData = $form.formToArray(false, elements); + + assert.deepEqual(formData, []); + assert.deepEqual(elements, []); + }); + }); + + describe("elements list", function () { + it("should push each contributing control once in data order and keep existing contents", function () { + const $form = $( + '
' + ); + const elements = ["kept"]; + + $form.formToArray(false, elements); + + assert.deepEqual(elements, [ + "kept", + $form.find('[name="t"]')[0], + $form.find("select")[0], + $form.find('[name="c"]')[0], + ]); + }); + + it("should throw a TypeError when elements has no push method", function () { + const $form = $('
'); + + const serialize = () => $form.formToArray(false, {}); + + assert.throws(serialize, TypeError); + }); + }); + }); + + describe("formSerialize", function () { + it("should produce one query-string pair per successful field", function () { + const $form = $("#form1"); + + const s = $form.formSerialize(); + + assert.ok(s.constructor == String, "type check"); + assert.ok(s.split("&").length == 13, "string array length"); + }); + + it("should serialize input elements that are not inside a form", function () { + const $fields = $("#pseudo *"); + + const s = $fields.fieldSerialize(); + + assert.ok(s.constructor == String, "type check"); + assert.ok(s.split("&").length == 3, "string array length"); + }); + + it("should return the $.param string of the first form's fields", function () { + const $form = $('
'); + + const serialized = $form.formSerialize(); + + assert.strictEqual(serialized, "a=1&b=2"); + }); + + it("should return an empty string for an empty selection and serialize only the first form", function () { + const $forms = $( + '
' + ); + + const empty = $(".missing-form").formSerialize(); + const serialized = $forms.formSerialize(); + + assert.strictEqual(empty, ""); + assert.strictEqual(serialized, "first=1"); + }); + + it("should encode spaces per jQuery version", function () { + const $form = $('
'); + + const serialized = $form.formSerialize(); + + // jQuery before 3.0 encodes a space as "+" in $.param; later versions use "%20". + const space = Number($.fn.jquery.split(".")[0]) < 3 ? "+" : "%20"; + assert.strictEqual(serialized, `a=x${space}y`); + }); + + it("should order the clicked image in place only when semantic is true", function () { + const $form = $( + '
' + ); + $form[0].clk = $form.find('[type="image"]')[0]; + $form[0].clk_x = 3; + $form[0].clk_y = 4; + + const semantic = $form.formSerialize(true); + const plain = $form.formSerialize(); + + assert.strictEqual(semantic, "a=1&map=go&map.x=3&map.y=4&b=2"); + assert.strictEqual(plain, "a=1&b=2&map=go&map.x=3&map.y=4"); + }); + + it("should send the file name when a file is selected", function () { + const $form = $('
'); + selectFiles($form.find('[type="file"]')[0], ["x.txt"]); + + const serialized = $form.formSerialize(); + + assert.strictEqual(serialized, "a=1&up=x.txt"); + }); + }); + + describe("fieldValue", function () { + it("should be used by formToArray, fieldSerialize and fieldValue when a page overrides it", function () { + const $form = $('
'); + const saved = $.fieldValue; + $.fieldValue = function () { + return "over"; + }; + + try { + const results = [ + $form.formToArray()[0].value, + $form.find("input").fieldSerialize(), + $form.find("input").fieldValue(), + ]; + + assert.deepEqual(results, ["over", "a=over", ["over"]]); + } finally { + $.fieldValue = saved; + } + }); + + it("should return null for a control inside a disabled fieldset", function () { + const input = $('
').find("input")[0]; + + const value = $.fieldValue(input); + + assert.strictEqual(value, null); + }); + + // #600: the document and text nodes have no tag name. + it("should return no values for nodes without a tag name", function () { + const $nodes = $([document, document.createTextNode("text")]); + + const values = $nodes.fieldValue(false); + + assert.deepEqual(values, ["", ""]); + }); + + it("should return null for an unselected select when success is not required", function () { + const select = $('')[0]; + select.selectedIndex = -1; + + const value = $.fieldValue(select, false); + + assert.strictEqual(value, null); + }); + + it("should use option text when an empty value attribute is unspecified", function () { + const select = $('')[0]; + Object.defineProperty(select.options[0], "attributes", { + configurable: true, + value: { value: { specified: false } }, + }); + + const value = $.fieldValue(select); + + assert.strictEqual(value, "Label"); + }); + + it("should omit unsuccessful controls by default", function () { + const $fields = $( + '
' + ).find(":input"); + $fields.filter("select")[0].selectedIndex = -1; + + const values = $fields.fieldValue(); + + assert.deepEqual(values, []); + }); + + it("should normalize line endings in scalar values", function () { + const $textarea = $(''); + + const values = $textarea.fieldValue(); + + assert.deepEqual(values, ["first\r\nsecond"]); + }); + + it("should return an empty array for an empty selection", function () { + const $fields = $(); + + const values = $fields.fieldValue(); + + assert.deepEqual(values, []); + }); + + it("should treat any falsy successful other than undefined as false", function () { + const $checkbox = $(''); + + const values = [null, 0, ""].map((successful) => $checkbox.fieldValue(successful)); + + assert.deepEqual(values, [["v"], ["v"], ["v"]]); + }); + + it("should return an empty array for a select-one whose selected option is disabled", function () { + const select = $( + '' + )[0]; + + const value = $.fieldValue(select); + + assert.deepEqual(value, []); + }); + + it("should return null for button-type controls and an unclicked image", function () { + const $form = $( + '
' + ); + + const values = $form + .find("input, button") + .get() + .map((el) => $.fieldValue(el)); + + assert.deepEqual(values, [null, null, null]); + }); + + it("should return the value of unnamed and disabled controls when successful is false", function () { + const unnamed = $('')[0]; + const disabled = $('')[0]; + + const values = [$.fieldValue(unnamed, false), $.fieldValue(disabled, false)]; + + assert.deepEqual(values, ["x", "y"]); + }); + + it("should return the value of the clicked submit button", function () { + const $form = $('
'); + const submit = $form.find("input")[0]; + $form[0].clk = submit; + + const value = $.fieldValue(submit); + + assert.strictEqual(value, "Go"); + }); + + it("should return null for a document and a text node by default", function () { + const text = document.createTextNode("text"); + + const values = [$.fieldValue(document), $.fieldValue(text)]; + + assert.deepEqual(values, [null, null]); + }); + + it("should return only successful values when successful is true", function () { + const expectedCheckbox = ["8", "10"]; + const expectedMultiple = ["3", "4"]; + + const input = $("#fieldTest input").fieldValue(true); + const anyField = $("#fieldTest :input").fieldValue(true); + const hidden = $("#fieldTest input:hidden").fieldValue(true); + const password = $("#fieldTest :password").fieldValue(true); + const radio = $("#fieldTest :radio").fieldValue(true); + const select = $("#fieldTest select").fieldValue(true); + const checkbox = $("#fieldTest :checkbox").fieldValue(true); + const multiple = $("#fieldTest [name=B]").fieldValue(true); + + assert.ok("5" == input[0], "input"); + assert.ok("1" == anyField[0], ":input"); + assert.ok("5" == hidden[0], ":hidden"); + assert.ok("14" == password[0], ":password"); + assert.ok("12" == radio[0], ":radio"); + assert.ok("1" == select[0], "select"); + assert.ok( + checkbox.length == expectedCheckbox.length, + "result size check (checkbox): " + checkbox.length + "=" + expectedCheckbox.length + ); + for (let i = 0; i < checkbox.length; i++) { + assert.ok(checkbox[i] == expectedCheckbox[i], expectedCheckbox[i]); + } + assert.ok( + multiple.length == expectedMultiple.length, + "result size check (select-multiple): " + multiple.length + "=" + expectedMultiple.length + ); + for (let i = 0; i < multiple.length; i++) { + assert.ok(multiple[i] == expectedMultiple[i], expectedMultiple[i]); + } + }); + + it("should return every value when successful is false", function () { + const expectedCheckbox = ["8", "9", "10"]; + const expectedRadio = ["11", "12", "13"]; + const expectedMultiple = ["3", "4"]; + + const input = $("#fieldTest input").fieldValue(false); + const anyField = $("#fieldTest :input").fieldValue(false); + const hidden = $("#fieldTest input:hidden").fieldValue(false); + const password = $("#fieldTest :password").fieldValue(false); + const select = $("#fieldTest select").fieldValue(false); + const checkbox = $("#fieldTest :checkbox").fieldValue(false); + const radio = $("#fieldTest :radio").fieldValue(false); + const multiple = $("#fieldTest [name=B]").fieldValue(false); + + assert.ok("5" == input[0], "input"); + assert.ok("1" == anyField[0], ":input"); + assert.ok("5" == hidden[0], ":hidden"); + assert.ok("14" == password[0], ":password"); + assert.ok("1" == select[0], "select"); + assert.ok( + checkbox.length == expectedCheckbox.length, + "result size check (checkbox): " + checkbox.length + "=" + expectedCheckbox.length + ); + for (let i = 0; i < checkbox.length; i++) { + assert.ok(checkbox[i] == expectedCheckbox[i], expectedCheckbox[i]); + } + assert.ok( + radio.length == expectedRadio.length, + "result size check (radio): " + radio.length + "=" + expectedRadio.length + ); + for (let i = 0; i < radio.length; i++) { + assert.ok(radio[i] == expectedRadio[i], expectedRadio[i]); + } + assert.ok( + multiple.length == expectedMultiple.length, + "result size check (select-multiple): " + multiple.length + "=" + expectedMultiple.length + ); + for (let i = 0; i < multiple.length; i++) { + assert.ok(multiple[i] == expectedMultiple[i], expectedMultiple[i]); + } + }); + }); + + describe("fieldSerialize", function () { + // Shared Assert step: the serialized pairs match `expected`, in order. + function assertPairs(serialized, expected) { + const result = serialized.split("&"); + + assert.ok( + result.length == expected.length, + "result size check: " + result.length + "=" + expected.length + ); + for (let i = 0; i < result.length; i++) { + assert.ok(result[i] == expected[i], expected[i] + " = " + result[i]); + } + } + + it("should serialize only successful inputs when successful is true", function () { + const expected = ["C=5", "D=6", "F=8", "F=10", "G=12", "H=14"]; + + const result = $("#fieldTest input").fieldSerialize(true); + + assertPairs(result, expected); + }); + + it("should serialize only successful fields of every kind when successful is true", function () { + const expected = ["A=1", "B=3", "B=4", "C=5", "D=6", "E=7", "F=8", "F=10", "G=12", "H=14"]; + + const result = $("#fieldTest :input").fieldSerialize(true); + + assertPairs(result, expected); + }); + + it("should serialize every field when successful is false", function () { + const expected = [ + "A=1", + "B=3", + "B=4", + "C=5", + "D=6", + "E=7", + "F=8", + "F=9", + "F=10", + "G=11", + "G=12", + "G=13", + "H=14", + "I=15", + "J=16", + ]; + + const result = $("#fieldTest :input").fieldSerialize(false); + + assertPairs(result, expected); + }); + + it("should serialize the selected options of a select-multiple", function () { + const expected = ["B=3", "B=4"]; + + const result = $("#fieldTest [name=B]").fieldSerialize(true); + + assertPairs(result, expected); + }); + + it("should serialize only checked checkboxes when successful is true", function () { + const expected = ["F=8", "F=10"]; + + const result = $("#fieldTest :checkbox").fieldSerialize(true); + + assertPairs(result, expected); + }); + + it("should serialize every checkbox when successful is false", function () { + const expected = ["F=8", "F=9", "F=10"]; + + const result = $("#fieldTest :checkbox").fieldSerialize(false); + + assertPairs(result, expected); + }); + + it("should serialize only the checked radio when successful is true", function () { + const expected = ["G=12"]; + + const result = $("#fieldTest :radio").fieldSerialize(true); + + assertPairs(result, expected); + }); + + it("should serialize every radio when successful is false", function () { + const expected = ["G=11", "G=12", "G=13"]; + + const result = $("#fieldTest :radio").fieldSerialize(false); + + assertPairs(result, expected); + }); + + it("should ignore unnamed fields and encode repeated select values", function () { + const $fields = $( + '
' + ).find(":input"); + + const result = $fields.fieldSerialize(); + + // jQuery before 3.0 encodes a space as "+" in $.param; later versions use "%20". + const space = Number($.fn.jquery.split(".")[0]) < 3 ? "+" : "%20"; + assert.strictEqual(result, `choice=a${space}b&choice=c`); + }); + + it("should skip unnamed fields when successful is false", function () { + const $fields = $(''); + + const result = $fields.fieldSerialize(false); + + assert.strictEqual(result, "a=1"); + }); + + it("should return an empty string for an empty selection", function () { + const $fields = $(); + + const result = $fields.fieldSerialize(); + + assert.strictEqual(result, ""); + }); + + it("should serialize a file input's value string", function () { + const $input = $(''); + selectFiles($input[0], ["x.txt"]); + + const result = $input.fieldSerialize(); + + assert.strictEqual(result, "up=C%3A%5Cfakepath%5Cx.txt"); + }); + + it("should skip forms", function () { + const $form = $('
'); + + const result = $form.fieldSerialize(); + + assert.strictEqual(result, ""); + }); + }); +}); diff --git a/test/suite/submission.test.js b/test/suite/submission.test.js new file mode 100644 index 0000000..b0dcc61 --- /dev/null +++ b/test/suite/submission.test.js @@ -0,0 +1,2454 @@ +/* global scriptCount */ + +import { assert, describe, it } from "vitest"; +import { + resetFixture, + submitAndSettle, + captureAjaxOptions, + withUserAgent, + withDocumentUrl, + withAjaxStub, + withAjaxSettings, + selectFiles, + formHidingParentNode, + buildForm, +} from "./helpers.js"; + +function makeForm(html) { + return $(html).appendTo("#main"); +} + +function absolute(path) { + return new URL(path, window.location.href).href; +} + +function pageUrl() { + return window.location.href.split("#")[0]; +} + +// Returns the FormData body the upload transport sets in its beforeSend. +function uploadBody(settings) { + const received = {}; + settings.beforeSend({}, received); + + return received.data; +} + +function majorVersion() { + return Number($.fn.jquery.split(".")[0]); +} + +// Calls ajaxSubmit with `args` through a stubbed $.ajax and returns the settings it received +// (undefined when no request started). `respond` may answer the request or return the jqXHR; +// `onReturn` receives what ajaxSubmit returned. +function submitWith($form, args, respond, onReturn) { + const ajax = $.ajax; + let settings; + $.ajax = function (received) { + settings = received; + const jqXHR = respond ? respond(received) : undefined; + return jqXHR || {}; + }; + + try { + const result = $form.ajaxSubmit.apply($form, args); + if (onReturn) { + onReturn(result); + } + } finally { + $.ajax = ajax; + } + + return settings; +} + +describe("form", function () { + resetFixture(); + + describe("ajaxSubmit", function () { + describe("non-upload options", function () { + it("should return an empty selection without starting a request", async function () { + let requests = 0; + const $empty = $(".missing-form"); + + await withAjaxStub( + function () { + requests++; + }, + async function () { + const result = $empty.ajaxSubmit(); + await Promise.resolve(); + + assert.strictEqual(result, $empty, "returns the original selection"); + assert.strictEqual(requests, 0, "does not request"); + } + ); + }); + + it("should throw a clear error before any event when jQuery has no $.ajax", function () { + const $form = makeForm('
'); + const events = []; + $form.on("form-pre-serialize", (event) => events.push(event.type)); + const ajax = $.ajax; + + let error; + try { + $.ajax = undefined; + $form.ajaxSubmit(); + } catch (thrown) { + error = thrown; + } finally { + $.ajax = ajax; + } + + assert.strictEqual( + error.message, + "jquery.form: ajaxSubmit needs the full jQuery build; this jQuery has no $.ajax" + ); + assert.deepEqual(events, []); + }); + + it("should accept the url, data, dataType and success shorthand arguments", async function () { + const extraData = { source: "shorthand" }; + let ajaxOptions; + let successData; + + await withAjaxStub( + function (options) { + ajaxOptions = options; + options.success("ok", "success", {}); + return {}; + }, + async function () { + $("#form3").ajaxSubmit("ajax/shorthand.html", extraData, "text", function (data) { + successData = data; + }); + await Promise.resolve(); + + assert.strictEqual(ajaxOptions.url, "ajax/shorthand.html", "url"); + assert.strictEqual(ajaxOptions.dataType, "text", "dataType"); + assert.ok(ajaxOptions.data.includes("source=shorthand"), "extra data"); + assert.strictEqual(successData, "ok", "success callback"); + } + ); + }); + + [ + [false, "ajax/text.html"], + [undefined, "ajax/text.html"], + ].forEach(function ([value, expectedUrl]) { + it("should normalize the url when options are " + String(value), async function () { + let ajaxOptions; + + await withAjaxStub( + function (options) { + ajaxOptions = options; + return {}; + }, + async function () { + $("#form3").ajaxSubmit(value); + await Promise.resolve(); + + assert.ok(ajaxOptions.url.endsWith(expectedUrl), "form action"); + } + ); + }); + }); + + it("should allow form-pre-serialize to veto before serialization", async function () { + let requests = 0; + let serialized = false; + const $form = $("#form3"); + const formToArray = $form.formToArray; + $form.one("form-pre-serialize", function (_event, _form, _options, veto) { + veto.veto = true; + }); + $form.formToArray = function () { + serialized = true; + return formToArray.apply(this, arguments); + }; + + try { + await withAjaxStub( + function () { + requests++; + }, + async function () { + $form.ajaxSubmit(); + await Promise.resolve(); + + assert.strictEqual(serialized, false, "does not serialize"); + assert.strictEqual(requests, 0, "does not request"); + } + ); + } finally { + $form.formToArray = formToArray; + $form.off("form-pre-serialize"); + } + }); + + it("should allow beforeSerialize to veto the request", async function () { + let requests = 0; + let callbackForm; + const opts = { + beforeSerialize: function ($form) { + callbackForm = $form; + return false; + }, + }; + + await withAjaxStub( + function () { + requests++; + }, + async function () { + const $form = $("#form3"); + $form.ajaxSubmit(opts); + await Promise.resolve(); + + assert.strictEqual(callbackForm, $form, "callback form"); + assert.strictEqual(requests, 0, "does not request"); + } + ); + }); + + it("should allow form-submit-validate to veto the request", async function () { + let requests = 0; + let submittedData; + const $form = $("#form3"); + $form.one("form-submit-validate", function (_event, data, _form, _options, veto) { + submittedData = data; + veto.veto = true; + }); + + try { + await withAjaxStub( + function () { + requests++; + }, + async function () { + $form.ajaxSubmit(); + await Promise.resolve(); + + assert.ok(Array.isArray(submittedData), "validation receives form data"); + assert.strictEqual(requests, 0, "does not request"); + } + ); + } finally { + $form.off("form-submit-validate"); + } + }); + + [ + ["object", { source: "object" }], + [ + "function", + function (formData) { + assert.ok(Array.isArray(formData), "function receives form data"); + return { source: "function" }; + }, + ], + ].forEach(function ([label, data]) { + it("should append extra data supplied as an " + label, async function () { + let ajaxOptions; + + await withAjaxStub( + function (options) { + ajaxOptions = options; + return {}; + }, + async function () { + $("#form3").ajaxSubmit({ data: data, type: "post" }); + await Promise.resolve(); + + assert.ok(ajaxOptions.data.includes("source=" + label), "serialized extra data"); + assert.deepEqual(ajaxOptions.extraData, { source: label }, "retains extra data"); + } + ); + }); + }); + + it("should append serialized data to a GET url and clear the request body", async function () { + let ajaxOptions; + + await withAjaxStub( + function (options) { + ajaxOptions = options; + return {}; + }, + async function () { + $("#form3").ajaxSubmit({ type: "get", url: "ajax/text.html?existing=1" }); + await Promise.resolve(); + + assert.ok(ajaxOptions.url.includes("?existing=1&"), "preserves existing query"); + assert.ok(ajaxOptions.url.includes("a="), "appends form data"); + assert.strictEqual(ajaxOptions.data, null, "clears request body"); + } + ); + }); + + it("should put serialized data in the POST request body", async function () { + let ajaxOptions; + + await withAjaxStub( + function (options) { + ajaxOptions = options; + return {}; + }, + async function () { + $("#form3").ajaxSubmit({ type: "post" }); + await Promise.resolve(); + + assert.strictEqual(ajaxOptions.type, "post", "request method"); + assert.ok(ajaxOptions.data.includes("a="), "request body"); + } + ); + }); + + it("should reset and clear the form before running success", async function () { + const $form = $("#form3"); + const $name = $form.find("[name=a]"); + const seen = []; + $name.val("changed"); + + await withAjaxStub( + function (options) { + options.success("ok", "success", {}); + return {}; + }, + async function () { + $form.ajaxSubmit({ + resetForm: true, + clearForm: true, + success: function () { + seen.push($name.val()); + }, + }); + await Promise.resolve(); + + assert.deepEqual(seen, [""], "maintenance callbacks precede success"); + } + ); + }); + + it("should replace the target and call success with the replacement as context", async function () { + const $target = $("#targetDiv").html("old"); + let callbackContext; + + await withAjaxStub( + function (options) { + options.success("
new
", "success", {}); + return {}; + }, + async function () { + $("#form3").ajaxSubmit({ + target: $target, + replaceTarget: true, + success: function () { + callbackContext = this; + }, + }); + await Promise.resolve(); + + assert.strictEqual($("#targetDiv").length, 0, "removes old target"); + assert.strictEqual($("#replacement").text(), "new", "inserts response"); + assert.strictEqual(callbackContext.id, "targetDiv", "original target context"); + } + ); + }); + + it("should run a success callback array with the configured context and form", async function () { + const context = { name: "callback context" }; + const calls = []; + const $form = $("#form3"); + + await withAjaxStub( + function (options) { + options.success("ok", "success", {}); + return {}; + }, + async function () { + $form.ajaxSubmit({ + context: context, + success: [ + function (_data, _status, _xhr, callbackForm) { + calls.push({ context: this, form: callbackForm }); + }, + function (_data, _status, _xhr, callbackForm) { + calls.push({ context: this, form: callbackForm }); + }, + ], + }); + await Promise.resolve(); + + assert.strictEqual(calls.length, 2, "all success callbacks"); + assert.strictEqual(calls[0].context.name, context.name, "first context"); + assert.strictEqual(calls[1].context, calls[0].context, "shared context"); + assert.strictEqual(calls[0].form, $form, "form argument"); + } + ); + }); + + it("should wrap error and complete with context and the form argument", async function () { + const context = { name: "callback context" }; + const xhr = { status: 500 }; + const seen = {}; + const $form = $("#form3"); + + await withAjaxStub( + function (options) { + options.error(xhr, "error", "broken"); + options.complete(xhr, "error"); + return xhr; + }, + async function () { + $form.ajaxSubmit({ + context: context, + error: function () { + seen.error = { context: this, args: Array.from(arguments) }; + }, + complete: function () { + seen.complete = { context: this, args: Array.from(arguments) }; + }, + }); + await Promise.resolve(); + + assert.strictEqual(seen.error.context.name, context.name, "error context"); + assert.deepEqual(seen.error.args, [xhr, "error", "broken", $form], "error arguments"); + assert.strictEqual(seen.complete.context, seen.error.context, "complete context"); + assert.deepEqual(seen.complete.args, [xhr, "error", $form], "complete arguments"); + } + ); + }); + + it("should store the jqXHR and notify listeners after starting the request", async function () { + const jqXHR = { readyState: 1 }; + let notified; + const $form = $("#form3"); + $form.one("form-submit-notify", function (_event, form, options) { + notified = { form: form, options: options, stored: $form.data("jqxhr") }; + }); + + try { + await withAjaxStub( + function () { + return jqXHR; + }, + async function () { + const opts = { type: "post" }; + $form.ajaxSubmit(opts); + await Promise.resolve(); + + assert.strictEqual($form.data("jqxhr"), jqXHR, "stored jqXHR"); + assert.strictEqual(notified.form, $form, "notified form"); + assert.strictEqual(notified.stored, jqXHR, "stores before notify"); + assert.strictEqual(notified.options.type, "post", "notified options"); + } + ); + } finally { + $form.off("form-submit-notify").removeData("jqxhr"); + } + }); + }); + + describe("target", function () { + it("should load the response into a target given as a selector", async function () { + $("#targetDiv").empty(); + const opts = { target: "#targetDiv" }; + + const seen = await submitAndSettle(opts, () => $("#form3").ajaxSubmit(opts)); + + assert.ok(seen.success, "post-callback"); + assert.ok($("#targetDiv").text().match("Lorem ipsum"), "targetDiv updated"); + }); + + it("should load the response into a target given as a jQuery object", async function () { + const $target = $("#targetDiv"); + $target.empty(); + const opts = { target: $target }; + + const seen = await submitAndSettle(opts, () => $("#form2").ajaxSubmit(opts)); + + assert.ok(seen.success, "post-callback"); + assert.ok($("#targetDiv").text().match("Lorem ipsum"), "targetDiv updated"); + }); + + it("should load the response into a target given as a DOM element", async function () { + $("#targetDiv").empty(); + const opts = { target: $("#targetDiv")[0] }; + + const seen = await submitAndSettle(opts, () => $("#form2").ajaxSubmit(opts)); + + assert.ok(seen.success, "post-callback"); + assert.ok($("#targetDiv").text().match("Lorem ipsum"), "targetDiv updated"); + }); + + it("should insert what dataFilter returns into the target", async function () { + $("#targetDiv").empty(); + const opts = { + target: "#targetDiv", + dataFilter: (data) => "filtered " + data.length, + }; + + const seen = await submitAndSettle(opts, () => $("#form2").ajaxSubmit(opts)); + + assert.ok(seen.success, "post-callback"); + assert.match($("#targetDiv").text(), /^filtered \d+$/); + }); + + it("should run each script of a loaded document exactly once", async function () { + $("#targetDiv").empty(); + const opts = { + target: "#targetDiv", + url: "ajax/doc-with-scripts.html?" + new Date().getTime(), + }; + + const seen = await submitAndSettle(opts, () => $("#form2").ajaxSubmit(opts)); + + assert.ok(seen.success, "success-callback"); + assert.ok($("#targetDiv").text().match("Lorem ipsum"), "targetDiv updated"); + assert.ok(typeof unitTestVariable1 != "undefined", "first script block executed"); + assert.ok(typeof unitTestVariable2 != "undefined", "second script block executed"); + assert.ok(typeof scriptCount != "undefined", "third script block executed"); + assert.ok(scriptCount == 1, "scripts executed once: " + scriptCount); + }); + }); + + describe("target with a parsed response", function () { + [ + ["a JSON array", ['']], + ["a JSON object", { html: '' }], + ].forEach(function ([label, data]) { + it("should not insert " + label + " but still call success", async function () { + window.targetPayload = 0; + const $target = $('
kept
').appendTo("#main"); + const $form = $('
').appendTo("#main"); + const successes = []; + + captureAjaxOptions( + $form, + { target: $target, success: (response) => successes.push(response) }, + (settings) => settings.success(data, "success", {}) + ); + await new Promise((resolve) => setTimeout(resolve, 50)); + + assert.strictEqual($target.html(), "kept"); + assert.deepEqual(successes, [data]); + assert.strictEqual(window.targetPayload, 0); + }); + }); + }); + + describe("callbacks", function () { + it("should call beforeSubmit with the field array and the form", async function () { + const opts = {}; + + const seen = await submitAndSettle(opts, () => $("#form3").ajaxSubmit(opts)); + + assert.ok(seen.beforeSubmit, "pre-submit callback"); + assert.ok(seen.beforeSubmit.data.constructor == Array, "type check array"); + assert.ok(seen.beforeSubmit.$form.jquery, "type check jQuery"); + assert.ok( + seen.beforeSubmit.$form[0].tagName.toLowerCase() == "form", + 'jQuery arg == "form": ' + seen.beforeSubmit.$form[0].tagName.toLowerCase() + ); + }); + + it("should call success with the response text and status text", async function () { + const opts = {}; + + const seen = await submitAndSettle(opts, () => $("#form3").ajaxSubmit(opts)); + + assert.ok(seen.success, "post-submit callback"); + assert.ok(seen.success[0].match("Lorem ipsum"), "responseText"); + assert.ok(seen.success[1] == "success", "statusText"); + }); + + it("should treat a function argument as the success callback", async function () { + let called = false; + + await new Promise(function (resolve) { + $("#form3").ajaxSubmit(function () { + called = true; + resolve(); + }); + }); + + assert.ok(called, "callback hit"); + }); + + it("should call beforeSubmit with fields in document order when semantic is true", async function () { + const testData = ["a", "b", "c", "d", "e", "f"]; + const opts = { semantic: true }; + + const seen = await submitAndSettle(opts, () => $("#form2").ajaxSubmit(opts)); + + assert.ok(seen.beforeSubmit, "pre-submit callback"); + assert.ok(seen.beforeSubmit.data.constructor == Array, "type check"); + assert.ok(seen.beforeSubmit.$form.jquery, "type check jQuery"); + for (let i = 0; i < seen.beforeSubmit.data.length; i++) { + assert.ok(seen.beforeSubmit.data[i].name == testData[i], "match value at index=" + i); + } + }); + + it("should not send the request when beforeSubmit returns false", function () { + const seen = { beforeSubmit: null, success: false }; + const opts = { + beforeSubmit: function (a, jq) { + seen.beforeSubmit = { data: a, $form: jq }; + return false; + }, + success: function () { + seen.success = true; + }, + }; + + $("#form3").ajaxSubmit(opts); + + assert.ok(seen.beforeSubmit, "pre-submit callback"); + assert.ok(seen.beforeSubmit.data.constructor == Array, "type check"); + assert.ok(seen.beforeSubmit.$form.jquery, "type check jQuery"); + assert.ok(!seen.success, "should not hit this post-submit callback"); + }); + + it("should call success when the request succeeds", async function () { + $("#targetDiv").empty(); + const opts = {}; + + const seen = await submitAndSettle(opts, () => $("#form3").ajaxSubmit(opts)); + + assert.ok(seen.success, "post-callback"); + }); + + it("should call error and not success when the request fails", async function () { + $("#targetDiv").empty(); + const opts = { url: "ajax/404.html" }; + + const seen = await submitAndSettle(opts, () => $("#form3").ajaxSubmit(opts)); + + assert.ok(seen.error, "error-callback"); + assert.ok(!seen.success, "should not hit post-submit callback"); + }); + + it("should pass status, xhr and the form to success", async function () { + $("#targetDiv").empty(); + const opts = {}; + let $testForm; + + const seen = await submitAndSettle(opts, () => { + $testForm = $("#form3").ajaxSubmit(opts); + }); + + assert.ok(seen.success, "success callback invoked"); + assert.ok(seen.success[1] === "success", "status === success"); + assert.ok(typeof seen.success[2] != "undefined", "third arg: " + typeof seen.success[2]); + assert.ok(!!seen.success[2] != false, "xhr != false"); + assert.ok(seen.success[2].status, "xhr.status == " + seen.success[2].status); + assert.ok(seen.success[3] === $testForm, "$form param is valid"); + }); + + it("should call success with a success status when forceSync is true", async function () { + $("#targetDiv").empty(); + const opts = { forceSync: true }; + + const seen = await submitAndSettle(opts, () => $("#form3").ajaxSubmit(opts)); + + assert.ok(seen.success, "success callback invoked"); + assert.ok(seen.success[1] === "success", "status === success"); + }); + }); + + describe("dataType", function () { + it("should parse a json response into an object", async function () { + const opts = { url: "ajax/json.json", dataType: "json" }; + + const seen = await submitAndSettle(opts, () => $("#form2").ajaxSubmit(opts)); + + assert.ok(typeof seen.success[0] == "object", "json data type"); + assert.ok(seen.success[0].name == "jquery-test", "json data contents"); + }); + + it("should evaluate a script response", async function () { + const opts = { + url: "ajax/script.txt?" + new Date().getTime(), // don't let ie cache it + dataType: "script", + }; + + const seen = await submitAndSettle(opts, () => $("#form2").ajaxSubmit(opts)); + + assert.ok(typeof formScriptTest == "function", "script evaluated"); + // jQuery 4 loads async script requests through a script tag, so no response text arrives. + if (Number($.fn.jquery.split(".")[0]) < 4) { + assert.ok(seen.success[0].match("formScriptTest"), "script returned"); + } + }); + + it("should parse an xml response into a document", async function () { + const opts = { url: "ajax/test.xml", dataType: "xml" }; + + const seen = await submitAndSettle(opts, () => $("#form2").ajaxSubmit(opts)); + + assert.ok(typeof seen.success[0] == "object", "data type xml"); + assert.ok($("test", seen.success[0]).length == 3, "xml data query"); + }); + + it("should leave a json text response for the caller to evaluate", async function () { + const opts = { url: "ajax/json.txt" }; + + const seen = await submitAndSettle(opts, () => $("#form2").ajaxSubmit(opts)); + + assert.ok(seen.success, "post-callback"); + const data = eval.call(window, "(" + seen.success[0] + ")"); + assert.ok(data.name == "jquery-test", "evaled response"); + }); + }); + + describe("action and url", function () { + it("should honor query args already present in the action attribute", async function () { + const opts = {}; + + const seen = await submitAndSettle(opts, () => $("#form5").ajaxSubmit(opts)); + + assert.ok(seen.success, "post callback"); + }); + + it("should submit a pseudo-form using the given url and type", async function () { + const opts = { url: "ajax/text.html", type: "post" }; + + const seen = await submitAndSettle(opts, () => $("#pseudo").ajaxSubmit(opts)); + + assert.ok(seen.beforeSubmit, "pre-submit callback"); + assert.ok(seen.beforeSubmit.data.constructor == Array, "type check"); + assert.ok(seen.beforeSubmit.$form.jquery, "type check jQuery"); + assert.ok(seen.beforeSubmit.$form[0].tagName.toLowerCase() == "div", 'jQuery arg == "div"'); + assert.ok(seen.success, "post-submit callback"); + }); + + // Each case submits a form whose action is unusual and checks that it still reaches + // beforeSerialize without throwing. + [ + ["a naked hash", "#actionTest1"], + ["a hash only", "#actionTest2"], + ["an empty", "#actionTest3"], + ["a missing", "#actionTest4"], + ].forEach(function ([label, selector]) { + it("should submit a form with " + label + " action", function () { + let url = null; + const opts = { + beforeSerialize: function ($f, o) { + url = o.url; + }, + }; + + assert.doesNotThrow(() => $(selector).ajaxSubmit(opts), "ajaxSubmit passed"); + + assert.ok(url !== null, "beforeSerialize called"); + }); + }); + + it("should use the page URL when a control named action shadows a missing action", function () { + const $form = $('
'); + + const settings = captureAjaxOptions($form.appendTo("#main"), {}); + + assert.strictEqual(settings.url, window.location.href.split("#")[0]); + }); + + it("should use the page URL for a raw action attribute that is only a fragment", function () { + const $form = $('
'); + + const settings = captureAjaxOptions($form.appendTo("#main"), {}); + + assert.strictEqual(settings.url, window.location.href.split("#")[0]); + }); + + it("should build a GET url for a raw action attribute that is only a fragment", function () { + const $form = $( + '
' + ); + + const settings = captureAjaxOptions($form.appendTo("#main"), {}); + + assert.ok(settings.url.startsWith(window.location.href.split("#")[0]), settings.url); + assert.match(settings.url, /[?&]action=x$/); + }); + + [ + ["ajax/text.html#frag", "ajax/text.html?a=1#frag"], + ["ajax/text.html?b=2#frag", "ajax/text.html?b=2&a=1#frag"], + ].forEach(function ([url, expected]) { + it("should put the GET query before the fragment of " + url, function () { + const $form = $('
').appendTo("#main"); + + const settings = captureAjaxOptions($form, { type: "GET", url: url }); + + assert.strictEqual(settings.url, expected); + }); + }); + + it("should use the default AJAX type when a control named method shadows the form", function () { + const $form = $('
'); + + const settings = captureAjaxOptions($form.appendTo("#main"), {}); + + assert.strictEqual(settings.type, $.ajaxSettings.type); + }); + + [ + ["an empty user agent", ""], + ["IE on a non-HTTPS page", "Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11.0)"], + ].forEach(function ([label, userAgent]) { + it("should use about:blank as the iframe source for " + label, function () { + const $form = $('
').appendTo("#main"); + + const settings = withUserAgent(userAgent, () => captureAjaxOptions($form, {})); + + assert.strictEqual(settings.iframeSrc, "about:blank"); + }); + }); + + it("should use javascript:false as the iframe source for IE on an HTTPS page", function () { + const $form = $('
').appendTo("#main"); + const userAgent = "Mozilla/5.0 (Windows NT 10.0; Trident/7.0; rv:11.0)"; + + const settings = withDocumentUrl("https://example.test/form", () => + withUserAgent(userAgent, () => captureAjaxOptions($form, {})) + ); + + assert.strictEqual(settings.iframeSrc, "javascript:false"); + }); + }); + + describe("serialization options", function () { + it("should serialize extra data traditionally when asked", function () { + const $form = $('
').appendTo("#main"); + + const settings = captureAjaxOptions($form, { + data: { list: ["a", "b"] }, + traditional: true, + }); + + assert.strictEqual(settings.data, "list=a&list=b"); + }); + + it("should submit only extra data when the form has no fields", function () { + const $form = $('
').appendTo("#main"); + + const settings = captureAjaxOptions($form, { data: { only: "extra" } }); + + assert.strictEqual(settings.data, "only=extra"); + }); + }); + + describe("argument shapes", function () { + it("should not trigger events or call the callback when the selection is empty", function () { + const events = []; + let called = false; + $(document).on("form-pre-serialize.empty form-submit-notify.empty", function (event) { + events.push(event.type); + }); + + try { + $(".missing-form").ajaxSubmit(function () { + called = true; + }); + } finally { + $(document).off(".empty"); + } + + assert.deepEqual(events, []); + assert.strictEqual(called, false); + }); + + it("should not throw when the selection is empty and options are null", function () { + const run = () => $(".missing-form").ajaxSubmit(null); + + assert.doesNotThrow(run); + }); + + it("should throw a TypeError before any event when options are null", function () { + const $form = makeForm('
'); + let triggered = false; + $form.on("form-pre-serialize", function () { + triggered = true; + }); + + const run = () => submitWith($form, [null]); + + assert.throws(run, TypeError); + assert.strictEqual(triggered, false); + }); + + it("should keep the default success when the shorthand fourth argument is not a function", async function () { + const $form = makeForm('
'); + const calls = []; + const globalSuccess = function () { + calls.push(arguments.length); + }; + + await withAjaxSettings({ success: globalSuccess }, function () { + submitWith($form, ["ajax/text.html", undefined, undefined, "not a function"], (s) => + s.success("ok", "success", {}) + ); + }); + + assert.deepEqual(calls, [4]); + }); + + it("should send no extra data when the shorthand data is undefined", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, ["ajax/other.html"]); + + assert.strictEqual(settings.url, "ajax/other.html"); + assert.strictEqual(settings.data, "a=1"); + assert.strictEqual(settings.extraData, undefined); + }); + + [true, 5].forEach(function (value) { + it("should treat " + value + " as default options", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [value]); + + assert.strictEqual(settings.url, absolute("ajax/text.html")); + assert.strictEqual(settings.type, "post"); + assert.strictEqual(settings.data, "a=1"); + }); + }); + + it("should ignore the shorthand arguments when options is an object", function () { + const $form = makeForm( + '
' + ); + let called = false; + const onSuccess = function () { + called = true; + }; + + const settings = submitWith($form, [{}, { extra: "x" }, "json", onSuccess], (s) => + s.success("ok", "success", {}) + ); + + assert.strictEqual(settings.data, "a=1"); + assert.strictEqual(settings.dataType, undefined); + assert.strictEqual(called, false); + }); + + it("should throw a TypeError after the veto points when type is null", function () { + const $form = makeForm('
'); + let beforeSubmitCalled = false; + const options = { + type: null, + beforeSubmit: function () { + beforeSubmitCalled = true; + }, + }; + + const run = () => submitWith($form, [options]); + + assert.throws(run, TypeError); + assert.strictEqual(beforeSubmitCalled, true); + }); + }); + + describe("method and type", function () { + it("should use options.method as the type on the $.ajax path", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [{ method: "put" }]); + + assert.strictEqual(settings.type, "put"); + assert.strictEqual(settings.method, "put"); + assert.strictEqual(settings.data, "a=1"); + }); + + it("should use the lowercase form method when the method attribute is uppercase", function () { + const $form = makeForm('
'); + + const settings = submitWith($form, [{}]); + + assert.strictEqual(settings.type, "post"); + }); + + it("should submit with GET when the form has no method attribute, even with a global POST type", async function () { + const $form = makeForm('
'); + let settings; + + await withAjaxSettings({ type: "POST" }, function () { + settings = submitWith($form, [{}]); + }); + + assert.strictEqual(settings.type, "get"); + assert.strictEqual(settings.data, null); + assert.strictEqual(settings.url, absolute("ajax/text.html") + "?a=1"); + }); + + ["put", "delete"].forEach(function (method) { + it("should submit with GET when the method attribute is " + method, function () { + const $form = makeForm('
'); + + const settings = submitWith($form, [{}]); + + assert.strictEqual(settings.type, "get"); + }); + }); + + it("should send a body when the method attribute is dialog", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [{}]); + + assert.strictEqual(settings.type, "dialog"); + assert.strictEqual(settings.data, "a=1"); + }); + + it("should use the raw method attribute when a control named method shadows the form", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [{}]); + + assert.strictEqual(settings.type, "PUT"); + }); + + it("should use the default AJAX type when a pseudo-form has no type", function () { + const $div = makeForm('
'); + + const settings = submitWith($div, [{ url: "ajax/text.html" }]); + + assert.strictEqual(settings.type, $.ajaxSettings.type); + assert.strictEqual(settings.url, "ajax/text.html?a=1"); + }); + + ["PUT", "DELETE"].forEach(function (type) { + it("should put the query in the body for " + type, function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [{ type: type }]); + + assert.strictEqual(settings.url, absolute("ajax/text.html")); + assert.strictEqual(settings.data, "a=1"); + }); + }); + + it("should send a GET method option over a POST type in the url", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [{ method: "GET", type: "POST" }]); + + assert.strictEqual(settings.type, "GET"); + assert.strictEqual(settings.url, absolute("ajax/text.html") + "?a=1"); + assert.strictEqual(settings.data, null); + }); + + it("should send the method option when method and type conflict", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [{ method: "POST", type: "GET" }]); + + assert.strictEqual(settings.url, absolute("ajax/text.html")); + assert.strictEqual(settings.data, "a=1"); + }); + }); + + describe("url resolution", function () { + it("should submit to the page url when the form has no action attribute", function () { + const $form = makeForm('
'); + + const settings = submitWith($form, [{}]); + + assert.strictEqual(settings.url, pageUrl()); + }); + + it("should submit to the page url when the action attribute is empty", function () { + const $form = makeForm('
'); + + const settings = submitWith($form, [{}]); + + assert.strictEqual(settings.url, pageUrl()); + }); + + ["#", "#x"].forEach(function (action) { + it("should submit to the page url when the action is " + action, function () { + const $form = makeForm('
'); + + const settings = submitWith($form, [{}]); + + assert.strictEqual(settings.url, pageUrl()); + }); + }); + + it("should drop the fragment of the form action", function () { + const $form = makeForm('
'); + + const settings = submitWith($form, [{}]); + + assert.strictEqual(settings.url, absolute("ajax/text.html")); + }); + + it("should append the GET query to a form action without its fragment", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [{}]); + + assert.strictEqual(settings.url, absolute("ajax/text.html") + "?a=1"); + }); + + it("should trim a raw action attribute when a control named action shadows the form", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [{}]); + + assert.strictEqual(settings.url, "ajax/text.html"); + }); + + it("should pass a caller url to $.ajax unchanged when it has spaces or a fragment", function () { + const $form = makeForm('
'); + + const settings = submitWith($form, [{ url: " ajax/other.html#frag " }]); + + assert.strictEqual(settings.url, " ajax/other.html#frag "); + }); + + it("should submit a pseudo-form without a url to the page url", function () { + const $div = makeForm("
"); + + const settings = submitWith($div, [{ type: "post" }]); + + assert.strictEqual(settings.url, pageUrl()); + }); + + it("should keep a caller iframeSrc", function () { + const $form = makeForm('
'); + + const settings = submitWith($form, [{ iframeSrc: "ajax/text.html" }]); + + assert.strictEqual(settings.iframeSrc, "ajax/text.html"); + }); + + [ + [false, "post"], + [false, "get"], + ["", "post"], + ["", "get"], + ].forEach(function ([url, method]) { + it( + "should submit to the form action when the url is " + + JSON.stringify(url) + + " and the form uses " + + method, + function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [url]); + + assert.ok( + String(settings.url).startsWith(absolute("ajax/text.html")), + String(settings.url) + ); + } + ); + }); + + [false, ""].forEach(function (url) { + it( + "should submit to the form action when the url option is " + JSON.stringify(url), + function () { + const $form = makeForm('
'); + const options = { url: url, type: "post" }; + + const settings = submitWith($form, [options]); + + assert.strictEqual(settings.url, absolute("ajax/text.html")); + assert.strictEqual(settings.type, "post"); + assert.strictEqual(options.url, url); + } + ); + }); + }); + + describe("options merge", function () { + it("should leave the caller's options object unchanged after a submit", function () { + const $form = makeForm( + '
' + ); + const success = function () {}; + const error = function () {}; + const complete = function () {}; + const data = { extra: "x" }; + const options = { success, error, complete, data, url: "ajax/other.html", type: "GET" }; + + submitWith($form, [options]); + + assert.deepEqual(Object.keys(options), [ + "success", + "error", + "complete", + "data", + "url", + "type", + ]); + assert.strictEqual(options.success, success); + assert.strictEqual(options.error, error); + assert.strictEqual(options.complete, complete); + assert.strictEqual(options.data, data); + assert.deepEqual(data, { extra: "x" }); + assert.strictEqual(options.url, "ajax/other.html"); + assert.strictEqual(options.type, "GET"); + }); + + it("should copy nested plain objects but keep jQuery objects and elements by reference", function () { + const $form = makeForm('
'); + const headers = { "X-Test": "1" }; + const $target = $("#targetDiv"); + const element = $target[0]; + + const settings = submitWith($form, [{ headers: headers, target: $target, el: element }]); + + assert.notStrictEqual(settings.headers, headers); + assert.deepEqual(settings.headers, headers); + assert.strictEqual(settings.target, $target); + assert.strictEqual(settings.el, element); + }); + + it("should not let an undefined option override a default", function () { + const $form = makeForm('
'); + + const settings = submitWith($form, [{ url: undefined, iframeSrc: undefined }]); + + assert.strictEqual(settings.url, absolute("ajax/text.html")); + assert.strictEqual(settings.iframeSrc, "about:blank"); + }); + + it("should call beforeSend, success and complete with the caller's context object on a request", async function () { + const context = { name: "context" }; + const seen = {}; + const record = (name) => + function () { + seen[name] = this; + }; + + await new Promise(function (resolve) { + $("#form3").ajaxSubmit({ + context: context, + beforeSend: record("beforeSend"), + success: record("success"), + complete: function () { + seen.complete = this; + resolve(); + }, + }); + }); + + assert.strictEqual(seen.beforeSend, context); + assert.strictEqual(seen.success, context); + assert.strictEqual(seen.complete, context); + }); + + it("should call callbacks with the given context object", function () { + const $form = makeForm('
'); + const context = { name: "context" }; + let seen; + + submitWith( + $form, + [ + { + context: context, + success: function () { + seen = this; + }, + }, + ], + (s) => s.success("ok", "success", {}) + ); + + assert.strictEqual(seen, context); + }); + + it("should pass the form to a global ajaxSetup success", async function () { + const $form = makeForm('
'); + let args; + const globalSuccess = function () { + args = Array.from(arguments); + }; + + await withAjaxSettings({ success: globalSuccess }, function () { + submitWith($form, [{}], (s) => s.success("ok", "success", "xhr")); + }); + + assert.deepEqual(args, ["ok", "success", "xhr", $form]); + }); + + it("should not pass the form to a global ajaxSetup error", async function () { + let settled; + + const args = await withAjaxSettings( + { + error: function () { + settled(Array.from(arguments).length); + }, + }, + function () { + return new Promise(function (resolve) { + settled = resolve; + $("#form3").ajaxSubmit({ url: "ajax/404.html" }); + }); + } + ); + + assert.strictEqual(args, 3); + }); + }); + + describe("veto points and hooks", function () { + it("should pass the selection and the merged options to form-pre-serialize handlers", function () { + const $form = makeForm('
'); + let seen; + $form.on("form-pre-serialize", function (_event, form, options, veto) { + seen = { form, options, veto }; + }); + + const settings = submitWith($form, [{}]); + + assert.strictEqual(seen.form, $form); + assert.strictEqual(seen.options, settings); + assert.deepEqual(seen.veto, {}); + }); + + it("should return the selection and keep the stored jqXHR when form-pre-serialize vetoes", function () { + const $form = makeForm('
'); + const earlier = { earlier: true }; + let beforeSerializeCalled = false; + $form.data("jqxhr", earlier); + $form.on("form-pre-serialize", function (_event, _form, _options, veto) { + veto.veto = true; + }); + const options = { + beforeSerialize: function () { + beforeSerializeCalled = true; + }, + }; + let result; + + const settings = submitWith($form, [options], null, (r) => (result = r)); + + assert.strictEqual(result, $form); + assert.strictEqual(settings, undefined); + assert.strictEqual(beforeSerializeCalled, false); + assert.strictEqual($form.data("jqxhr"), earlier); + }); + + it("should still submit when plugin event handlers return false or prevent the default", function () { + const $form = makeForm('
'); + $form.on("form-pre-serialize", function () { + return false; + }); + $form.on("form-submit-validate", function (event) { + event.preventDefault(); + event.stopPropagation(); + }); + + const settings = submitWith($form, [{}]); + + assert.ok(settings); + }); + + it("should deliver plugin events to document handlers", function () { + const $form = makeForm('
'); + const events = []; + $(document).on( + "form-pre-serialize.bubble form-submit-validate.bubble form-submit-notify.bubble", + function (event) { + events.push(event.type); + } + ); + + try { + submitWith($form, [{}]); + } finally { + $(document).off(".bubble"); + } + + assert.deepEqual(events, [ + "form-pre-serialize", + "form-submit-validate", + "form-submit-notify", + ]); + }); + + it("should submit a detached form without document handlers seeing its events", function () { + const $form = $('
'); + const events = []; + $(document).on("form-pre-serialize.detached", function (_event, _form, _options, veto) { + events.push("seen"); + veto.veto = true; + }); + let settings; + + try { + settings = submitWith($form, [{}]); + } finally { + $(document).off(".detached"); + } + + assert.deepEqual(events, []); + assert.ok(settings); + }); + + it("should call beforeSerialize with the merged options as this", function () { + const $form = makeForm('
'); + let seen; + const options = { + beforeSerialize: function (_form, opts) { + seen = { self: this, opts }; + }, + }; + + const settings = submitWith($form, [options]); + + assert.strictEqual(seen.self, settings); + assert.strictEqual(seen.opts, settings); + }); + + [0, null, "", undefined].forEach(function (value) { + it("should continue when beforeSerialize returns " + JSON.stringify(value), function () { + const $form = makeForm('
'); + + const settings = submitWith($form, [{ beforeSerialize: () => value }]); + + assert.ok(settings); + }); + }); + + it("should use a url set by a form-pre-serialize handler", function () { + const $form = makeForm('
'); + $form.on("form-pre-serialize", function (_event, _form, options) { + options.url = "ajax/changed.html"; + }); + + const settings = submitWith($form, [{}]); + + assert.strictEqual(settings.url, "ajax/changed.html"); + }); + + it("should use a type set by beforeSerialize", function () { + const $form = makeForm( + '
' + ); + const options = { + beforeSerialize: function (_form, opts) { + opts.type = "GET"; + }, + }; + + const settings = submitWith($form, [options]); + + assert.strictEqual(settings.url, absolute("ajax/text.html") + "?a=1"); + assert.strictEqual(settings.data, null); + }); + + it("should call beforeSubmit with the merged options as this and the options argument", function () { + const $form = makeForm('
'); + let seen; + const options = { + beforeSubmit: function (_a, _form, opts) { + seen = { self: this, opts }; + }, + }; + + const settings = submitWith($form, [options]); + + assert.strictEqual(seen.self, settings); + assert.strictEqual(seen.opts, settings); + }); + + it("should return the selection and skip form-submit-validate when beforeSubmit returns false", function () { + const $form = makeForm('
'); + let validated = false; + $form.on("form-submit-validate", function () { + validated = true; + }); + let result; + + const settings = submitWith( + $form, + [{ beforeSubmit: () => false }], + null, + (r) => (result = r) + ); + + assert.strictEqual(result, $form); + assert.strictEqual(settings, undefined); + assert.strictEqual(validated, false); + }); + + it("should send the fields as beforeSubmit leaves them", function () { + const $form = makeForm( + '
' + ); + const options = { + beforeSubmit: function (a) { + a.splice(0, 1); + a[0].value = "changed"; + a.push({ name: "c", value: "3" }); + }, + }; + + const settings = submitWith($form, [options]); + + assert.strictEqual(settings.data, "b=changed&c=3"); + }); + + it("should pass the same veto object to both veto events", function () { + const $form = makeForm('
'); + const seen = {}; + $form.on("form-pre-serialize", function (_event, _form, _options, veto) { + seen.pre = veto; + }); + $form.on("form-submit-validate", function (_event, a, form, options, veto) { + seen.validate = { a, form, options, veto }; + }); + + const settings = submitWith($form, [{}]); + + assert.strictEqual(seen.validate.veto, seen.pre); + assert.strictEqual(seen.validate.form, $form); + assert.strictEqual(seen.validate.options, settings); + assert.ok(Array.isArray(seen.validate.a)); + }); + + [ + [ + "form-pre-serialize vetoes", + ($form) => + $form.on("form-pre-serialize", (_e, _f, _o, veto) => { + veto.veto = true; + }), + {}, + ], + ["beforeSerialize returns false", () => {}, { beforeSerialize: () => false }], + ["beforeSubmit returns false", () => {}, { beforeSubmit: () => false }], + [ + "form-submit-validate vetoes", + ($form) => + $form.on("form-submit-validate", (_e, _a, _f, _o, veto) => { + veto.veto = true; + }), + {}, + ], + ].forEach(function ([label, arrange, options]) { + it("should return the selection without a request when " + label, function () { + const $form = makeForm('
'); + arrange($form); + let result; + + const settings = submitWith($form, [options], null, (r) => (result = r)); + + assert.strictEqual(result, $form); + assert.strictEqual(settings, undefined); + }); + }); + + it("should run the submit steps in order", function () { + const $form = makeForm('
'); + const steps = []; + $form.on("form-pre-serialize", () => steps.push("form-pre-serialize")); + $form.on("form-submit-validate", () => steps.push("form-submit-validate")); + $form.on("form-submit-notify", () => + steps.push("form-submit-notify:" + ($form.data("jqxhr") ? "stored" : "missing")) + ); + const options = { + beforeSerialize: () => steps.push("beforeSerialize"), + data: function () { + steps.push("data"); + return {}; + }, + beforeSubmit: () => steps.push("beforeSubmit"), + }; + + submitWith($form, [options], () => steps.push("$.ajax")); + + assert.deepEqual(steps, [ + "form-pre-serialize", + "beforeSerialize", + "data", + "beforeSubmit", + "form-submit-validate", + "$.ajax", + "form-submit-notify:stored", + ]); + }); + }); + + describe("extra data", function () { + it("should call the data function with the merged options as this, even when beforeSubmit vetoes", function () { + const $form = makeForm('
'); + const seen = []; + let merged; + const options = { + beforeSerialize: function (_form, opts) { + merged = opts; + }, + data: function (a) { + seen.push({ self: this, a }); + return {}; + }, + beforeSubmit: function (a) { + seen.push({ a }); + return false; + }, + }; + + submitWith($form, [options]); + + assert.strictEqual(seen.length, 2); + assert.strictEqual(seen[0].self, merged); + assert.strictEqual(seen[0].a, seen[1].a); + }); + + [undefined, null, "", 0, false].forEach(function (value) { + it("should keep a caller extraData when data is " + String(value), function () { + const $form = makeForm('
'); + + const settings = submitWith($form, [{ data: value, extraData: { kept: "1" } }]); + + assert.deepEqual(settings.extraData, { kept: "1" }); + }); + }); + + it("should not send a caller extraData on the $.ajax path", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [{ extraData: { kept: "1" } }]); + + assert.strictEqual(settings.data, "a=1"); + }); + + it("should ignore a data option changed in beforeSubmit on the $.ajax path", function () { + const $form = makeForm( + '
' + ); + const options = { + data: { x: "1" }, + beforeSubmit: function (_a, _form, opts) { + opts.data = { y: "2" }; + }, + }; + + const settings = submitWith($form, [options]); + + assert.strictEqual(settings.data, "a=1&x=1"); + }); + + it("should handle a data function that returns undefined per jQuery version", function () { + const $form = makeForm( + '
' + ); + + const run = () => submitWith($form, [{ data: () => undefined }]); + + if (majorVersion() < 3) { + assert.throws(run, TypeError); + } else { + assert.strictEqual(run().data, "a=1"); + } + }); + + it("should append an array of name/value pairs as fields", function () { + const $form = makeForm( + '
' + ); + const data = [ + { name: "x", value: "1" }, + { name: "x", value: "2" }, + ]; + + const settings = submitWith($form, [{ data: data }]); + + assert.strictEqual(settings.data, "a=1&x=1&x=2"); + }); + + it("should serialize null extra values per jQuery version", function () { + const $form = makeForm('
'); + + const settings = submitWith($form, [{ data: { n: null } }]); + + if (majorVersion() < 3) { + assert.strictEqual(settings.data, "n=null"); + } else { + assert.strictEqual(settings.data, "n="); + } + }); + + it("should send only the fields when data is an empty object", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [{ data: {} }]); + + assert.strictEqual(settings.data, "a=1"); + }); + + [ + ["the global setting", true, undefined, "a=1&list=x&list=y"], + ["traditional false over the global setting", true, false, "a=1&list%5B%5D=x&list%5B%5D=y"], + ].forEach(function ([label, global, traditional, expected]) { + it("should serialize extra data with " + label + " on the $.ajax path", async function () { + const $form = makeForm( + '
' + ); + let settings; + + await withAjaxSettings({ traditional: global }, function () { + settings = submitWith($form, [{ data: { list: ["x", "y"] }, traditional }]); + }); + + assert.strictEqual(settings.data, expected); + }); + }); + + it("should serialize upload extra data traditionally when the traditional option is set", function () { + const $form = makeForm( + '
' + ); + selectFiles($form.find("input")[0], ["a.txt"]); + + const settings = submitWith($form, [{ data: { list: ["x", "y"] }, traditional: true }]); + + assert.deepEqual(uploadBody(settings).getAll("list"), ["x", "y"]); + }); + + it("should send null extra values on the upload transport per jQuery version", function () { + const $form = makeForm( + '
' + ); + selectFiles($form.find("input")[0], ["a.txt"]); + + const settings = submitWith($form, [{ data: { n: null } }]); + + assert.strictEqual(uploadBody(settings).get("n"), majorVersion() < 3 ? "null" : ""); + }); + + it("should keep a caller contentType while sending a urlencoded body", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [{ contentType: "application/json", data: { b: 2 } }]); + + assert.strictEqual(settings.contentType, "application/json"); + assert.strictEqual(settings.data, "a=1&b=2"); + }); + + it("should send a query-string data option as its own fields", function () { + const $form = makeForm('
'); + + const settings = submitWith($form, [{ data: "x=1" }]); + + assert.strictEqual(settings.data, "x=1"); + }); + it("should append a query-string data option as-is to the fields", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [{ data: "x=1&y=%20" }]); + + assert.strictEqual(settings.data, "a=1&x=1&y=%20"); + }); + + it("should append a query-string data option to the url of a GET", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [{ data: "x=1" }]); + + assert.strictEqual(settings.url, absolute("ajax/text.html") + "?a=1&x=1"); + }); + }); + + describe("requestFormat json", function () { + const post = (markup) => + makeForm('
' + markup + "
"); + + it("should send the fields as a JSON body with repeated names as arrays", function () { + const $form = post( + '' + ); + + const settings = submitWith($form, [{ requestFormat: "json", contentType: "text/plain" }]); + + assert.deepEqual(JSON.parse(settings.data), { a: "1", t: ["x", "y", "z"] }); + assert.strictEqual(settings.contentType, "application/json; charset=UTF-8"); + assert.strictEqual(settings.url, absolute("ajax/text.html")); + }); + + it("should merge object data over the fields and keep __proto__ as a plain key", function () { + const $form = post(''); + + const settings = submitWith($form, [ + { requestFormat: "json", data: { a: "2", nested: { n: [1, 2] } } }, + ]); + + const body = JSON.parse(settings.data); + assert.strictEqual(Object.getPrototypeOf({}).polluted, undefined); + assert.deepEqual(Object.keys(body), ["a", "__proto__", "nested"]); + assert.strictEqual(body.a, "2"); + assert.deepEqual(body.nested, { n: [1, 2] }); + }); + + it("should merge only the own keys of the object a data function returns", function () { + const $form = post(''); + const data = Object.create({ inherited: "x" }); + data.own = "y"; + + const settings = submitWith($form, [{ requestFormat: "json", data: () => data }]); + + assert.deepEqual(JSON.parse(settings.data), { a: "1", own: "y" }); + }); + + it("should send the form through $.ajax as a JSON request", async function () { + const $form = $("#form3"); + let sent; + + await withAjaxStub( + function (options) { + sent = options; + return {}; + }, + async function () { + $form.ajaxSubmit({ requestFormat: "json" }); + await Promise.resolve(); + } + ); + + assert.strictEqual(typeof JSON.parse(sent.data), "object"); + assert.strictEqual(sent.contentType, "application/json; charset=UTF-8"); + }); + + [ + [ + "a GET method", + '
', + {}, + 'jquery.form: requestFormat "json" needs a method with a body, such as POST', + ], + [ + "string data", + '
', + { data: "x=1" }, + 'jquery.form: requestFormat "json" needs object data; a string data option is a query string', + ], + [ + "the iframe transport", + '
', + { iframe: true }, + 'jquery.form: requestFormat "json" cannot send files or use the iframe transport', + ], + ].forEach(function ([label, markup, options, message]) { + it("should throw a clear error with " + label, function () { + const $form = makeForm(markup); + + const run = () => submitWith($form, [$.extend({ requestFormat: "json" }, options)]); + + assert.throws(run, Error, message); + }); + }); + }); + + describe("request url and body", function () { + it("should encode spaces in the request body per jQuery version", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [{}]); + + assert.strictEqual(settings.data, majorVersion() < 3 ? "a=x+y" : "a=x%20y"); + }); + + it("should leave a bare ? when a GET form has no fields", function () { + const $form = makeForm('
'); + + const settings = submitWith($form, [{}]); + + assert.strictEqual(settings.url, absolute("ajax/text.html") + "?"); + }); + + it("should leave a trailing & when a GET url with a query has no fields", function () { + const $form = makeForm('
'); + + const settings = submitWith($form, [{ url: "ajax/text.html?b=2" }]); + + assert.strictEqual(settings.url, "ajax/text.html?b=2&"); + }); + + it("should pass the GET url with the query to the FormData transport", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [{}]); + + assert.ok(uploadBody(settings) instanceof FormData); + assert.strictEqual(settings.url, absolute("ajax/text.html") + "?a=1"); + }); + + it("should pass headers, timeout and beforeSend through to $.ajax", function () { + const $form = makeForm('
'); + const beforeSend = function () {}; + + const settings = submitWith($form, [ + { headers: { "X-Test": "1" }, timeout: 1234, beforeSend: beforeSend, cache: false }, + ]); + + assert.deepEqual(settings.headers, { "X-Test": "1" }); + assert.strictEqual(settings.timeout, 1234); + assert.strictEqual(settings.beforeSend, beforeSend); + assert.strictEqual(settings.cache, false); + }); + + it("should pass plugin-only options through to $.ajax", function () { + const $form = makeForm('
'); + const $target = $("#targetDiv"); + const options = { + target: $target, + resetForm: true, + clearForm: true, + semantic: true, + replaceTarget: true, + data: { x: "1" }, + }; + + const settings = submitWith($form, [options]); + + assert.strictEqual(settings.target, $target); + assert.strictEqual(settings.resetForm, true); + assert.strictEqual(settings.clearForm, true); + assert.strictEqual(settings.semantic, true); + assert.strictEqual(settings.replaceTarget, true); + assert.deepEqual(settings.extraData, { x: "1" }); + assert.strictEqual(settings.iframeSrc, "about:blank"); + }); + + it("should forward the filtering option", function () { + const $form = makeForm( + '
' + ); + + const settings = submitWith($form, [{ filtering: (el) => (el.name === "b" ? el : null) }]); + + assert.strictEqual(settings.data, "b=2"); + }); + }); + + describe("several selected forms", function () { + it("should trigger events on every selected form but submit the first form's fields", function () { + const $first = makeForm( + '
' + ); + const $second = makeForm( + '
' + ); + const $both = $first.add($second); + const seen = []; + $both.on("form-pre-serialize form-submit-notify", function (event) { + seen.push(event.type + ":" + $both.index(this)); + }); + let beforeSubmitForm; + + const settings = submitWith($both, [ + { beforeSubmit: (_a, form) => (beforeSubmitForm = form) }, + ]); + + assert.strictEqual(settings.data, "a=1"); + assert.strictEqual(settings.url, absolute("ajax/text.html")); + assert.strictEqual(beforeSubmitForm, $both); + assert.deepEqual(seen, [ + "form-pre-serialize:0", + "form-pre-serialize:1", + "form-submit-notify:0", + "form-submit-notify:1", + ]); + }); + + it("should store the jqXHR on every selected form", function () { + const $both = makeForm( + '
' + ); + const jqXHR = { readyState: 1 }; + + submitWith($both, [{}], () => jqXHR); + + assert.strictEqual($both.eq(0).data("jqxhr"), jqXHR); + assert.strictEqual($both.eq(1).data("jqxhr"), jqXHR); + }); + }); + + describe("responses", function () { + it("should not reset the form when the request fails", function () { + const $form = makeForm( + '
' + ); + $form.find("input").val("changed"); + + submitWith($form, [{ resetForm: true, error: () => {} }], (s) => + s.error({}, "error", "broken") + ); + + assert.strictEqual($form.find("input").val(), "changed"); + }); + + it("should forward includeHidden to clearForm", function () { + const $form = makeForm( + '
' + ); + + submitWith($form, [{ clearForm: true, includeHidden: true }], (s) => + s.success("ok", "success", {}) + ); + + assert.strictEqual($form.find("input").val(), ""); + }); + + it("should ignore target when a dataType is given", function () { + const $form = makeForm('
'); + const $target = $("#targetDiv").html("kept"); + const context = { name: "context" }; + const calls = []; + const options = { + target: $target, + dataType: "text", + context: context, + success: function () { + calls.push(this.name); + }, + }; + + submitWith($form, [options], (s) => s.success("new", "success", {})); + + assert.strictEqual($target.html(), "kept"); + assert.deepEqual(calls, ["context"]); + }); + + it("should resolve a target selector when the response arrives", function () { + const $form = makeForm('
'); + const settings = submitWith($form, [{ target: ".late-target" }]); + const $late = makeForm('
'); + + settings.success("late", "success", {}); + + assert.strictEqual($late.html(), "late"); + }); + + it("should not insert an XML document into the target", function () { + const $form = makeForm('
'); + const $target = $("#targetDiv").html("kept"); + const xml = new DOMParser().parseFromString("x", "application/xml"); + const successes = []; + + submitWith($form, [{ target: $target, success: (data) => successes.push(data) }], (s) => + s.success(xml, "success", {}) + ); + + assert.strictEqual($target.html(), "kept"); + assert.deepEqual(successes, [xml]); + }); + + it("should call success once per target element with the response arguments and without the context", function () { + const $form = makeForm('
'); + const $targets = makeForm('
'); + const xhr = { status: 200 }; + const calls = []; + const options = { + target: ".t", + context: { name: "context" }, + success: function () { + calls.push({ self: this, args: Array.from(arguments) }); + }, + }; + + submitWith($form, [options], (s) => s.success("x", "success", xhr)); + + assert.strictEqual(calls.length, 2); + assert.strictEqual(calls[0].self, $targets[0]); + assert.strictEqual(calls[1].self, $targets[1]); + assert.deepEqual(calls[0].args, ["x", "success", xhr, $form]); + }); + + it("should throw when a success array entry is not a function", function () { + const $form = makeForm('
'); + + const run = () => + submitWith($form, [{ success: [function () {}, "not a function"] }], (s) => + s.success("ok", "success", {}) + ); + + assert.throws(run, TypeError); + }); + + it("should apply dataFilter before inserting into the target", async function () { + const $target = $("#targetDiv").empty(); + + await new Promise(function (resolve) { + $("#form3").ajaxSubmit({ + target: $target, + dataFilter: () => "filtered", + success: resolve, + }); + }); + + assert.strictEqual($target.html(), "filtered"); + }); + + it("should call success with jQuery's settings object as this when no context is given", async function () { + const $form = $("#form3"); + let notified; + $form.one("form-submit-notify", (_event, _form, options) => (notified = options)); + + const self = await new Promise(function (resolve) { + $form.ajaxSubmit({ + success: function () { + resolve(this); + }, + }); + }); + + assert.notStrictEqual(self, notified); + assert.strictEqual(self.url, notified.url); + }); + + it("should call success when the target matches no elements", function () { + const $form = makeForm('
'); + let calls = 0; + + submitWith($form, [{ target: "#no-such-target", success: () => calls++ }], (s) => + s.success("x", "success", {}) + ); + + assert.strictEqual(calls, 1); + }); + + it("should call success once with jQuery's settings as this when the target matches nothing", async function () { + const $form = $("#form3"); + const calls = []; + + await new Promise(function (resolve) { + $form.ajaxSubmit({ + target: "#no-such-target", + success: function (data) { + calls.push([this, data]); + }, + complete: () => resolve(), + }); + }); + + assert.strictEqual(calls.length, 1); + assert.strictEqual(typeof calls[0][0].url, "string"); + assert.strictEqual(calls[0][0].nodeType, undefined); + assert.strictEqual(typeof calls[0][1], "string"); + }); + + it("should call every success callback when target is set and success is an array", function () { + const $form = makeForm('
'); + $("#targetDiv").empty(); + const calls = []; + + submitWith( + $form, + [{ target: "#targetDiv", success: [() => calls.push(1), () => calls.push(2)] }], + (s) => s.success("x", "success", {}) + ); + + assert.deepEqual(calls, [1, 2]); + }); + + it("should call every error callback given as an array", function () { + const $form = makeForm('
'); + const calls = []; + + submitWith($form, [{ error: [() => calls.push(1), () => calls.push(2)] }], (s) => + s.error({}, "error", "broken") + ); + + assert.deepEqual(calls, [1, 2]); + }); + + it("should call every complete callback given as an array", function () { + const $form = makeForm('
'); + const calls = []; + + submitWith($form, [{ complete: [() => calls.push(1), () => calls.push(2)] }], (s) => + s.complete({}, "success") + ); + + assert.deepEqual(calls, [1, 2]); + }); + + it("should give every error and complete callback in an array the form when a request fails", async function () { + const $form = $("#form3"); + const seen = []; + const record = (name) => + function () { + seen.push([name, arguments[arguments.length - 1]]); + }; + + await new Promise(function (resolve) { + $form.ajaxSubmit({ + url: "ajax/404.html", + error: [record("error1"), record("error2")], + complete: [record("complete1"), record("complete2"), () => resolve()], + }); + }); + + assert.deepEqual( + seen.map(([name]) => name), + ["error1", "error2", "complete1", "complete2"] + ); + seen.forEach(([name, $last]) => assert.strictEqual($last[0], $form[0], name)); + }); + + it("should call every success callback once per target element when success is an array", function () { + const $form = makeForm('
'); + const $targets = $('
').appendTo("#main"); + const calls = []; + + submitWith( + $form, + [ + { + target: $targets, + success: [ + function () { + calls.push([1, this]); + }, + function () { + calls.push([2, this]); + }, + ], + }, + ], + (s) => s.success("x", "success", {}) + ); + + assert.deepEqual(calls, [ + [1, $targets[0]], + [2, $targets[0]], + [1, $targets[1]], + [2, $targets[1]], + ]); + }); + }); + + describe("after the request starts", function () { + it("should notify with the final url and body", function () { + const $form = makeForm( + '
' + ); + let notified; + $form.on("form-submit-notify", (_event, _form, options) => (notified = options)); + + const settings = submitWith($form, [{}]); + + assert.strictEqual(notified, settings); + assert.strictEqual(notified.url, absolute("ajax/text.html") + "?a=1"); + assert.strictEqual(notified.data, null); + }); + + it("should store the beforeSend result per jQuery version and still notify when beforeSend returns false", function () { + const $form = makeForm('
'); + let notified = false; + $form.on("form-submit-notify", () => (notified = true)); + + $form.ajaxSubmit({ beforeSend: () => false }); + + const stored = $form.data("jqxhr"); + if (majorVersion() < 3) { + assert.strictEqual(stored, false); + } else { + assert.strictEqual(typeof stored.abort, "function"); + assert.strictEqual(stored.statusText, "canceled"); + } + assert.strictEqual(notified, true); + }); + }); + + describe("controls named like form members", function () { + // jQuery 1.7.2's selector engine calls getAttribute on the form itself, so it cannot run there. + it.skipIf(Number($.fn.jquery.split(".")[0]) < 3)( + "should submit when a control named getAttribute shadows the form", + function () { + const $form = $( + '
' + ).appendTo("#main"); + + const settings = captureAjaxOptions($form, {}); + + assert.strictEqual(settings.data, "getAttribute=x"); + assert.strictEqual(settings.type, "post"); + } + ); + + // jQuery 3's selector engine calls getElementsByTagName on the form for the file input lookup. + it.skipIf(Number($.fn.jquery.split(".")[0]) === 3)( + "should submit semantically when a control named getElementsByTagName shadows the form", + function () { + const $form = $( + buildForm('', "ajax/text.html") + ); + + const settings = captureAjaxOptions($form, { semantic: true }); + + assert.match(settings.url, /\?getElementsByTagName=x$/); + } + ); + + it("should throw a clear error when a control named parentNode hides the form's parent", function () { + const $form = $(formHidingParentNode()); + let settings; + + const submit = () => { + settings = captureAjaxOptions($form, {}); + }; + + assert.throws(submit, /control named "parentNode"/); + assert.strictEqual(settings, undefined); + }, 2000); + + it("should reset the form after success when a control named reset shadows the method", function () { + const $form = $( + '
' + ).appendTo("#main"); + $form.find("input").val("changed"); + + captureAjaxOptions($form, { resetForm: true }, (settings) => settings.success("ok")); + + assert.strictEqual($form.find("input").val(), "default"); + }); + }); + + describe("debug logging", function () { + function countLogs(run) { + const log = console.log; + let count = 0; + console.log = () => count++; + + try { + run(); + } finally { + console.log = log; + } + + return count; + } + + const vetoes = [ + [ + "form-pre-serialize", + ($form) => + $form.on("form-pre-serialize", (_e, _f, _o, veto) => { + veto.veto = true; + }), + {}, + ], + ["beforeSerialize", () => {}, { beforeSerialize: () => false }], + ["beforeSubmit", () => {}, { beforeSubmit: () => false }], + [ + "form-submit-validate", + ($form) => + $form.on("form-submit-validate", (_e, _a, _f, _o, veto) => { + veto.veto = true; + }), + {}, + ], + ]; + + it("should have debug off by default", function () { + const debug = $.fn.ajaxSubmit.debug; + + assert.strictEqual(debug, false); + }); + + it("should log nothing on a full submit or a parsed target response when debug is off", function () { + const $form = makeForm('
'); + + const count = countLogs(() => + submitWith($form, [{ target: "#targetDiv" }], (s) => s.success({}, "success", {})) + ); + + assert.strictEqual(count, 0); + }); + + vetoes.forEach(function ([label, arrange, options]) { + it("should log nothing when " + label + " vetoes and debug is off", function () { + const $form = makeForm('
'); + arrange($form); + + const count = countLogs(() => submitWith($form, [options])); + + assert.strictEqual(count, 0); + }); + + it("should log once when " + label + " vetoes and debug is on", function () { + const $form = makeForm('
'); + arrange($form); + $.fn.ajaxSubmit.debug = true; + let count; + + try { + count = countLogs(() => submitWith($form, [options])); + } finally { + $.fn.ajaxSubmit.debug = false; + } + + assert.strictEqual(count, 1); + }); + }); + + it("should log once before the transport and once for a parsed target response when debug is on", function () { + const $form = makeForm('
'); + $.fn.ajaxSubmit.debug = true; + let settings; + let counts; + + try { + counts = [ + countLogs(() => (settings = submitWith($form, [{ target: "#targetDiv" }]))), + countLogs(() => settings.success({}, "success", {})), + ]; + } finally { + $.fn.ajaxSubmit.debug = false; + } + + assert.deepEqual(counts, [1, 1]); + }); + }); + }); +}); diff --git a/test/suite/successful-controls.test.js b/test/suite/successful-controls.test.js new file mode 100644 index 0000000..9821501 --- /dev/null +++ b/test/suite/successful-controls.test.js @@ -0,0 +1,97 @@ +import { assert, describe, it } from "vitest"; +import { isSuccessful } from "../../src/successful-controls.js"; + +describe("successful controls", function () { + describe("isSuccessful", function () { + function control(html) { + return $(html)[0]; + } + + function inForm(html) { + return $("
" + html + "
").children()[0]; + } + + it("should accept a named text input", function () { + const el = control(''); + + const successful = isSuccessful(el, null); + + assert.strictEqual(successful, true); + }); + + it("should reject an unnamed or disabled control", function () { + const unnamed = control(""); + const disabled = control(''); + + const results = [isSuccessful(unnamed, null), isSuccessful(disabled, null)]; + + assert.deepEqual(results, [false, false]); + }); + + it("should read disabled from the property when the control cannot match selectors", function () { + const disabled = { name: "a", type: "text", disabled: true }; + const enabled = { name: "a", type: "text", disabled: false, tagName: "INPUT" }; + + const results = [isSuccessful(disabled, null), isSuccessful(enabled, null)]; + + assert.deepEqual(results, [false, true]); + }); + + it("should reject reset and plain buttons", function () { + const reset = control(''); + const button = control('', {}], - [ - "a named clicked submit button", - '', - { choice: "picked" }, - ], - ].forEach(function ([label, markup, expected]) { - it("should submit hidden values for " + label, async function () { - const $form = createIframeForm("ajax/iframe-text.html"); - $form[0].clk = $(markup).appendTo($form)[0]; - const submitted = {}; - inspectNativeSubmit($form, function (form) { - $(form) - .find('input[type="hidden"]') - .each(function () { - submitted[this.name] = this.value; - }); - }); - - await submitThroughIframe($form, { dataType: "text" }); - - assert.deepEqual(submitted, expected); - }); - }); - - it("should keep GET method and encoding when submitting with GET", async function () { - const $form = createIframeForm("ajax/iframe-text.html").attr("method", "get"); - let submitted; - inspectNativeSubmit($form, function (form) { - submitted = [form.getAttribute("method"), form.getAttribute("enctype")]; - }); - - const result = await submitThroughIframe($form, { dataType: "text" }); - - assert.deepEqual(submitted, ["get", null]); - assert.strictEqual(result.success[0].trim(), "iframe response"); - }); - - // #597: arrays and objects are sent as $.param sends them. - it("should submit array extraData values as separate fields", async function () { - const $form = createIframeForm("ajax/iframe-text.html"); - const submitted = []; - inspectNativeSubmit($form, function (form) { - $(form) - .find('input[type="hidden"]') - .each(function () { - submitted.push([this.name, this.value]); - }); - }); - - await submitThroughIframe($form, { data: { tags: ["a", "b"] }, dataType: "text" }); - - assert.deepEqual(submitted, [ - ["tags[]", "a"], - ["tags[]", "b"], - ]); - }); - - it("should submit nested extraData objects as bracketed fields", async function () { - const $form = createIframeForm("ajax/iframe-text.html"); - const submitted = []; - inspectNativeSubmit($form, function (form) { - $(form) - .find('input[type="hidden"]') - .each(function () { - submitted.push([this.name, this.value]); - }); - }); - - await submitThroughIframe($form, { - data: { meta: { owner: "Ada", tags: ["x"] }, plain: "a+b c" }, - dataType: "text", - }); - - assert.deepEqual(submitted, [ - ["meta[owner]", "Ada"], - ["meta[tags][]", "x"], - ["plain", "a+b c"], - ]); - }); - - // Starts an iframe upload whose native submit only records the generated hidden inputs and - // iframe, then aborts it. - async function submitAndAbort($form, options) { - const seen = {}; - $form[0].submit = function () { - seen.hidden = $(this) - .find('input[type="hidden"]') - .map(function () { - return [[this.name, this.value]]; - }) - .get(); - const target = this.getAttribute("target"); - seen.iframeSrc = $("iframe") - .filter((i, frame) => frame.name === target) - .attr("src"); - }; - - $form.ajaxSubmit($.extend({ iframe: true, forceSync: true, error: () => {} }, options)); - $form.data("jqxhr").abort(); - await new Promise((resolve) => setTimeout(resolve, 50)); - - return seen; - } - - const payload = '">'; - - [ - ["an extraData name", { extraData: { field: { name: payload, value: "v" } } }], - ["an extraData key", { extraData: { [payload]: "v" } }], - ].forEach(function ([label, options]) { - it("should submit " + label + " as text, not HTML", async function () { - window.iframePayload = 0; - const $form = createIframeForm("ajax/iframe-text.html"); - - const seen = await submitAndAbort($form, options); - - assert.deepEqual(seen.hidden, [[payload, "v"]]); - assert.strictEqual(window.iframePayload, 0); - }); - }); - - it("should submit a clicked button's name as text, not HTML", async function () { - window.iframePayload = 0; - const $form = createIframeForm("ajax/iframe-text.html"); - const $button = $('').appendTo("#main"); - const ajaxSubmit = $.fn.ajaxSubmit; - const success = function () {}; - let submittedOptions; - $.fn.ajaxSubmit = function (options) { - submittedOptions = options; - return this; - }; - - try { - $form.ajaxForm("/shorthand", { source: "test" }, "json", success); - $form.trigger("submit"); - - assert.strictEqual(submittedOptions.url, "/shorthand"); - assert.deepEqual(submittedOptions.data, { source: "test" }); - assert.strictEqual(submittedOptions.dataType, "json"); - assert.strictEqual(submittedOptions.success, success); - } finally { - $.fn.ajaxSubmit = ajaxSubmit; - } - }); - - it("should accept false as the shorthand URL without a success callback", function () { - const $form = $("
").appendTo("#main"); - const ajaxSubmit = $.fn.ajaxSubmit; - let submittedOptions; - $.fn.ajaxSubmit = function (options) { - submittedOptions = options; - return this; - }; - - try { - $form.ajaxForm(false); - $form.trigger("submit"); - - assert.strictEqual(submittedOptions.url, false); - assert.strictEqual(submittedOptions.success, undefined); - } finally { - $.fn.ajaxSubmit = ajaxSubmit; - } - }); - - it("should return an empty selection without binding handlers", function () { - const $missing = $(".missing-ajax-form"); - - const result = $missing.ajaxForm(); - - assert.strictEqual(result, $missing); - assert.strictEqual($._data(document, "events"), undefined); - }); - - describe("before the DOM is ready", function () { - // These tests fake `$.isReady`. jQuery 1.7.2 then re-fires its ready handlers, which closes - // the test page, so they only run where the collection has no native selector metadata. - const it = globalThis.it.skipIf(Number($.fn.jquery.split(".")[0]) < 3); - - function withDomNotReady(run) { - const isReady = $.isReady; - $.isReady = false; - - try { - return run(); - } finally { - $.isReady = isReady; - } - } - - it("should bind once ready when old jQuery selector metadata is present", async function () { - const $pending = $(".queued-ajax-form"); - $pending.selector = ".queued-ajax-form"; - - const result = withDomNotReady(() => $pending.ajaxForm()); - const $form = $('
').appendTo("#main"); - await new Promise((resolve) => setTimeout(resolve, 0)); - - assert.strictEqual(result, $pending); - assert.strictEqual($._data($form[0], "events").submit.length, 1); - }); - - it("should not queue an empty selection without selector metadata", async function () { - const $pending = $(".unqueued-ajax-form"); - - const result = withDomNotReady(() => $pending.ajaxForm()); - const $form = $('
').appendTo("#main"); - await new Promise((resolve) => setTimeout(resolve, 0)); - - assert.strictEqual(result, $pending); - assert.strictEqual($._data($form[0], "events"), undefined); - }); - }); - - it("should call beforeFormUnbind before replacing form handlers", function () { - const $form = $('
').appendTo("#main"); - const order = []; - $form.on("submit.form-plugin", function () { - order.push("old handler"); - }); - - $form.ajaxForm({ - beforeFormUnbind: function (forms, options) { - order.push("before unbind"); - assert.strictEqual(forms, $form); - assert.strictEqual(options.beforeFormUnbind instanceof Function, true); - assert.strictEqual($._data($form[0], "events").submit.length, 1); - }, - }); - - assert.deepEqual(order, ["before unbind"]); - assert.strictEqual($._data($form[0], "events").submit.length, 1); - }); - - it("should leave a canceled submit untouched", function () { - const $form = $('
').appendTo("#main"); - const ajaxSubmit = $.fn.ajaxSubmit; - let submissions = 0; - $.fn.ajaxSubmit = function () { - submissions++; - return this; - }; - $form.on("submit", function (event) { - event.preventDefault(); - }); - - try { - const event = $.Event("submit"); - $form.ajaxForm(); - $form.trigger(event); - - assert.strictEqual(event.isDefaultPrevented(), true); - assert.strictEqual(submissions, 0); - } finally { - $.fn.ajaxSubmit = ajaxSubmit; - } - }); - - it("should capture a submit button when nested content is clicked", function () { - const $form = $( - '
' - ).appendTo("#main"); - const button = $form.find("button")[0]; - - $form.ajaxForm(); - $form.find("span").trigger("click"); - - assert.strictEqual($form[0].clk, button); - }); - - // #588: a button without a type attribute is a submit button. - it("should capture a button without a type attribute", function () { - const $form = $( - '
' - ).appendTo("#main"); - const button = $form.find("button")[0]; - - $form.ajaxForm(); - $form.find("span").trigger("click"); - - assert.strictEqual($form[0].clk, button); - }); - - it("should ignore clicks outside submit controls", function () { - const $form = $("
Not a submit control
").appendTo("#main"); - - $form.ajaxForm(); - $form.find("span").trigger("click"); - - assert.strictEqual($form[0].clk, undefined); - }); - - [ - ["a text input", ''], - ["an element with a submit type attribute", 'Send'], - [ - "a submit button that belongs to no form", - '', - ], - ].forEach(function ([label, html]) { - it("should ignore clicks on " + label, function () { - const $form = $("
").append(html).appendTo("#main"); - $form.ajaxForm(); - - const click = () => $form.children().trigger("click"); - - assert.doesNotThrow(click); - assert.strictEqual($form[0].clk, undefined); - }); - }); - - // jQuery 3.7 removed the selection selector needed to scope delegated handlers. - it.fails("should scope delegated handlers to the selected forms", function () { - const $selected = $('
').appendTo("#main"); - const $unselected = $("
").appendTo("#main"); - const ajaxSubmit = $.fn.ajaxSubmit; - let submissions = 0; - $.fn.ajaxSubmit = function () { - submissions++; - return this; - }; - - try { - $selected.ajaxForm({ delegation: true }); - $unselected.trigger("submit"); - - assert.strictEqual(submissions, 0); - } finally { - $(document).off(".form-plugin"); - $.fn.ajaxSubmit = ajaxSubmit; - } - }); - - it("should capture image coordinates supplied by the click event", function () { - const $form = $('
').appendTo("#main"); - const $image = $form.find("input"); - const event = $.Event("click"); - event.offsetX = 14; - event.offsetY = 27; - - $form.ajaxForm(); - $image.trigger(event); - - assert.strictEqual($form[0].clk, $image[0]); - assert.strictEqual($form[0].clk_x, 14); - assert.strictEqual($form[0].clk_y, 27); - }); - - it("should derive image coordinates from its document offset", function () { - const $form = $('
').appendTo("#main"); - const $image = $form.find("input"); - const offset = $.fn.offset; - $.fn.offset = function () { - return { left: 10, top: 20 }; - }; - const event = $.Event("click"); - event.pageX = 31; - event.pageY = 58; - - try { - $form.ajaxForm(); - $image.trigger(event); - - assert.strictEqual($form[0].clk_x, 21); - assert.strictEqual($form[0].clk_y, 38); - } finally { - $.fn.offset = offset; - } - }); - - it("should derive image coordinates from element offsets without the offset helper", function () { - const $form = $('
').appendTo("#main"); - const $image = $form.find("input"); - const offset = $.fn.offset; - $.fn.offset = undefined; - Object.defineProperties($image[0], { - offsetLeft: { configurable: true, value: 7 }, - offsetTop: { configurable: true, value: 9 }, - }); - const event = $.Event("click"); - event.pageX = 19; - event.pageY = 24; - - try { - $form.ajaxForm(); - $image.trigger(event); - - assert.strictEqual($form[0].clk_x, 12); - assert.strictEqual($form[0].clk_y, 15); - } finally { - $.fn.offset = offset; - } - }); - - it("should clear captured submit details after the click window", async function () { - const $form = $('
').appendTo("#main"); - const $image = $form.find("input"); - const event = $.Event("click"); - event.offsetX = 4; - event.offsetY = 6; - $form.ajaxForm(); - $image.trigger(event); - - await new Promise((resolve) => setTimeout(resolve, 120)); - - assert.strictEqual($form[0].clk, null); - assert.strictEqual($form[0].clk_x, null); - assert.strictEqual($form[0].clk_y, null); - }); - - it("should call beforeSubmit and then success when the submit button is clicked", async function () { - const opts = {}; - - const seen = await submitAndSettle(opts, () => { - $("#form4").ajaxForm(opts); - $("#submitForm4")[0].click(); - }); - - assert.ok(seen.beforeSubmit, "pre-submit callback"); - assert.ok(seen.beforeSubmit.data.constructor == Array, "type check"); - assert.ok(seen.beforeSubmit.$form.jquery, "type check jQuery"); - assert.ok(seen.success, "post-submit callback"); - }); - - it("should include the value of the clicked submit button", async function () { - const opts = {}; - - const seen = await submitAndSettle(opts, () => { - $("#form4").ajaxForm(opts); - $("#submitForm4withName")[0].click(); - }); - - assert.ok(seen.beforeSubmit, "pre-callback"); - assert.ok(seen.beforeSubmit.data.constructor == Array, "type check"); - assert.ok(seen.beforeSubmit.$form.jquery, "type check jQuery"); - assert.ok( - arrayValue(seen.beforeSubmit.data, "form4inputName") !== undefined, - "submit button" - ); - }); - - it("should include the coordinates of a clicked image submit", async function () { - const opts = {}; - - const seen = await submitAndSettle(opts, () => { - $("#form4").ajaxForm(opts); - $("#form4imageSubmit")[0].click(); - }); - - assert.ok(seen.beforeSubmit, "pre-callback"); - assert.ok(seen.beforeSubmit.data.constructor == Array, "type check"); - assert.ok(seen.beforeSubmit.$form.jquery, "type check jQuery"); - assert.ok(arrayValue(seen.beforeSubmit.data, "myImage.x") !== undefined, "x coord"); - assert.ok(arrayValue(seen.beforeSubmit.data, "myImage.y") !== undefined, "y coord"); - }); - - it("should include image coordinates when semantic is true", async function () { - const opts = { semantic: true }; - - const seen = await submitAndSettle(opts, () => { - $("#form4").ajaxForm(opts); - $("#form4imageSubmit")[0].click(); - }); - - assert.ok(seen.beforeSubmit, "pre-callback"); - assert.ok(seen.beforeSubmit.data.constructor == Array, "type check"); - assert.ok(seen.beforeSubmit.$form.jquery, "type check jQuery"); - assert.ok(arrayValue(seen.beforeSubmit.data, "myImage.x") !== undefined, "x coord"); - assert.ok(arrayValue(seen.beforeSubmit.data, "myImage.y") !== undefined, "y coord"); - }); - - it("should load the response into the target div", async function () { - $("#targetDiv").empty(); - const opts = { target: "#targetDiv" }; - - const seen = await submitAndSettle(opts, () => { - $("#form4").ajaxForm(opts); - $("#submitForm4")[0].click(); - }); - - assert.ok(seen.beforeSubmit, "pre-callback"); - assert.ok(seen.beforeSubmit.data.constructor == Array, "type check"); - assert.ok(seen.beforeSubmit.$form.jquery, "type check jQuery"); - assert.ok(seen.success, "post-callback"); - assert.ok($("#targetDiv").text().match("Lorem ipsum"), "targetDiv updated"); - }); - - it("should submit once when ajaxForm is bound several times", async function () { - $("#targetDiv").empty(); - let beforeSubmitCalls = 0; - let successCalls = 0; - const opts = { - target: "#targetDiv", - beforeSubmit: function () { - beforeSubmitCalls++; - }, - success: function () { - successCalls++; - }, - }; - const settled = new Promise((resolve) => { - const success = opts.success; - opts.success = function () { - success.apply(this, arguments); - // Let any duplicate submissions from extra bindings land before asserting. - setTimeout(resolve, 100); - }; - }); - - $("#form8").ajaxForm(opts).ajaxForm(opts).ajaxForm(opts); - $("#submitForm8")[0].click(); - await settled; - - assert.strictEqual(beforeSubmitCalls, 1, "pre-callback"); - assert.strictEqual(successCalls, 1, "post-callback"); - }); - - it("should not submit after ajaxFormUnbind", async function () { - $("#targetDiv").empty(); - let callbacks = 0; - const opts = { - target: "#targetDiv", - beforeSubmit: function () { - callbacks++; - }, - success: function () { - callbacks++; - }, - }; - $("#form9") - .ajaxForm(opts) - .submit(function () { - return false; - }); - - $("#form9").ajaxFormUnbind(opts); - $("#submitForm9")[0].click(); - await new Promise((resolve) => setTimeout(resolve, 500)); - - assert.strictEqual(callbacks, 0, "no callbacks after unbind"); - }); - }); -}); diff --git a/vitest.config.mjs b/vitest.config.mjs index c389f0a..98b573f 100644 --- a/vitest.config.mjs +++ b/vitest.config.mjs @@ -27,7 +27,7 @@ function serveFiles(name, pattern, toPath, headers = {}) { }; } -// test/test.js requests fixtures by several relative paths (ajax/x, test/ajax/x). +// The suite requests fixtures by several relative paths (ajax/x, test/ajax/x). const ajaxFixtures = serveFiles( "ajax-fixtures", /\/ajax\/([\w.-]+)/, @@ -108,7 +108,7 @@ export default defineConfig({ { find: /^jquery\/dist\/jquery\.js$/, replacement: jqueryFile }, ], globals: true, - include: ["test/test.js"], + include: ["test/suite/**/*.test.js"], setupFiles: ["test/setup.js"], browser: browser(), },