bos@574: /*
bos@574: * jQuery Form Plugin
bos@574: * @requires jQuery v1.1 or later
bos@574: *
bos@574: * Examples at: http://malsup.com/jquery/form/
bos@574: * Dual licensed under the MIT and GPL licenses:
bos@574: * http://www.opensource.org/licenses/mit-license.php
bos@574: * http://www.gnu.org/licenses/gpl.html
bos@574: *
bos@574: * Revision: $Id$
bos@574: */
bos@574: (function($) {
bos@574: /**
bos@574: * ajaxSubmit() provides a mechanism for submitting an HTML form using AJAX.
bos@574: *
bos@574: * ajaxSubmit accepts a single argument which can be either a success callback function
bos@574: * or an options Object. If a function is provided it will be invoked upon successful
bos@574: * completion of the submit and will be passed the response from the server.
bos@574: * If an options Object is provided, the following attributes are supported:
bos@574: *
bos@574: * target: Identifies the element(s) in the page to be updated with the server response.
bos@574: * This value may be specified as a jQuery selection string, a jQuery object,
bos@574: * or a DOM element.
bos@574: * default value: null
bos@574: *
bos@574: * url: URL to which the form data will be submitted.
bos@574: * default value: value of form's 'action' attribute
bos@574: *
bos@574: * type: The method in which the form data should be submitted, 'GET' or 'POST'.
bos@574: * default value: value of form's 'method' attribute (or 'GET' if none found)
bos@574: *
bos@574: * data: Additional data to add to the request, specified as key/value pairs (see $.ajax).
bos@574: *
bos@574: * beforeSubmit: Callback method to be invoked before the form is submitted.
bos@574: * default value: null
bos@574: *
bos@574: * success: Callback method to be invoked after the form has been successfully submitted
bos@574: * and the response has been returned from the server
bos@574: * default value: null
bos@574: *
bos@574: * dataType: Expected dataType of the response. One of: null, 'xml', 'script', or 'json'
bos@574: * default value: null
bos@574: *
bos@574: * semantic: Boolean flag indicating whether data must be submitted in semantic order (slower).
bos@574: * default value: false
bos@574: *
bos@574: * resetForm: Boolean flag indicating whether the form should be reset if the submit is successful
bos@574: *
bos@574: * clearForm: Boolean flag indicating whether the form should be cleared if the submit is successful
bos@574: *
bos@574: *
bos@574: * The 'beforeSubmit' callback can be provided as a hook for running pre-submit logic or for
bos@574: * validating the form data. If the 'beforeSubmit' callback returns false then the form will
bos@574: * not be submitted. The 'beforeSubmit' callback is invoked with three arguments: the form data
bos@574: * in array format, the jQuery object, and the options object passed into ajaxSubmit.
bos@574: * The form data array takes the following form:
bos@574: *
bos@574: * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
bos@574: *
bos@574: * If a 'success' callback method is provided it is invoked after the response has been returned
bos@574: * from the server. It is passed the responseText or responseXML value (depending on dataType).
bos@574: * See jQuery.ajax for further details.
bos@574: *
bos@574: *
bos@574: * The dataType option provides a means for specifying how the server response should be handled.
bos@574: * This maps directly to the jQuery.httpData method. The following values are supported:
bos@574: *
bos@574: * 'xml': if dataType == 'xml' the server response is treated as XML and the 'success'
bos@574: * callback method, if specified, will be passed the responseXML value
bos@574: * 'json': if dataType == 'json' the server response will be evaluted and passed to
bos@574: * the 'success' callback, if specified
bos@574: * 'script': if dataType == 'script' the server response is evaluated in the global context
bos@574: *
bos@574: *
bos@574: * Note that it does not make sense to use both the 'target' and 'dataType' options. If both
bos@574: * are provided the target will be ignored.
bos@574: *
bos@574: * The semantic argument can be used to force form serialization in semantic order.
bos@574: * This is normally true anyway, unless the form contains input elements of type='image'.
bos@574: * If your form must be submitted with name/value pairs in semantic order and your form
bos@574: * contains an input of type='image" then pass true for this arg, otherwise pass false
bos@574: * (or nothing) to avoid the overhead for this logic.
bos@574: *
bos@574: *
bos@574: * When used on its own, ajaxSubmit() is typically bound to a form's submit event like this:
bos@574: *
bos@574: * $("#form-id").submit(function() {
bos@574: * $(this).ajaxSubmit(options);
bos@574: * return false; // cancel conventional submit
bos@574: * });
bos@574: *
bos@574: * When using ajaxForm(), however, this is done for you.
bos@574: *
bos@574: * @example
bos@574: * $('#myForm').ajaxSubmit(function(data) {
bos@574: * alert('Form submit succeeded! Server returned: ' + data);
bos@574: * });
bos@574: * @desc Submit form and alert server response
bos@574: *
bos@574: *
bos@574: * @example
bos@574: * var options = {
bos@574: * target: '#myTargetDiv'
bos@574: * };
bos@574: * $('#myForm').ajaxSubmit(options);
bos@574: * @desc Submit form and update page element with server response
bos@574: *
bos@574: *
bos@574: * @example
bos@574: * var options = {
bos@574: * success: function(responseText) {
bos@574: * alert(responseText);
bos@574: * }
bos@574: * };
bos@574: * $('#myForm').ajaxSubmit(options);
bos@574: * @desc Submit form and alert the server response
bos@574: *
bos@574: *
bos@574: * @example
bos@574: * var options = {
bos@574: * beforeSubmit: function(formArray, jqForm) {
bos@574: * if (formArray.length == 0) {
bos@574: * alert('Please enter data.');
bos@574: * return false;
bos@574: * }
bos@574: * }
bos@574: * };
bos@574: * $('#myForm').ajaxSubmit(options);
bos@574: * @desc Pre-submit validation which aborts the submit operation if form data is empty
bos@574: *
bos@574: *
bos@574: * @example
bos@574: * var options = {
bos@574: * url: myJsonUrl.php,
bos@574: * dataType: 'json',
bos@574: * success: function(data) {
bos@574: * // 'data' is an object representing the the evaluated json data
bos@574: * }
bos@574: * };
bos@574: * $('#myForm').ajaxSubmit(options);
bos@574: * @desc json data returned and evaluated
bos@574: *
bos@574: *
bos@574: * @example
bos@574: * var options = {
bos@574: * url: myXmlUrl.php,
bos@574: * dataType: 'xml',
bos@574: * success: function(responseXML) {
bos@574: * // responseXML is XML document object
bos@574: * var data = $('myElement', responseXML).text();
bos@574: * }
bos@574: * };
bos@574: * $('#myForm').ajaxSubmit(options);
bos@574: * @desc XML data returned from server
bos@574: *
bos@574: *
bos@574: * @example
bos@574: * var options = {
bos@574: * resetForm: true
bos@574: * };
bos@574: * $('#myForm').ajaxSubmit(options);
bos@574: * @desc submit form and reset it if successful
bos@574: *
bos@574: * @example
bos@574: * $('#myForm).submit(function() {
bos@574: * $(this).ajaxSubmit();
bos@574: * return false;
bos@574: * });
bos@574: * @desc Bind form's submit event to use ajaxSubmit
bos@574: *
bos@574: *
bos@574: * @name ajaxSubmit
bos@574: * @type jQuery
bos@574: * @param options object literal containing options which control the form submission process
bos@574: * @cat Plugins/Form
bos@574: * @return jQuery
bos@574: */
bos@574: $.fn.ajaxSubmit = function(options) {
bos@574: if (typeof options == 'function')
bos@574: options = { success: options };
bos@574:
bos@574: options = $.extend({
bos@574: url: this.attr('action') || window.location,
bos@574: type: this.attr('method') || 'GET'
bos@574: }, options || {});
bos@574:
bos@574: // hook for manipulating the form data before it is extracted;
bos@574: // convenient for use with rich editors like tinyMCE or FCKEditor
bos@574: var veto = {};
bos@574: $.event.trigger('form.pre.serialize', [this, options, veto]);
bos@574: if (veto.veto) return this;
bos@574:
bos@574: var a = this.formToArray(options.semantic);
bos@574: if (options.data) {
bos@574: for (var n in options.data)
bos@574: a.push( { name: n, value: options.data[n] } );
bos@574: }
bos@574:
bos@574: // give pre-submit callback an opportunity to abort the submit
bos@574: if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) return this;
bos@574:
bos@574: // fire vetoable 'validate' event
bos@574: $.event.trigger('form.submit.validate', [a, this, options, veto]);
bos@574: if (veto.veto) return this;
bos@574:
bos@574: var q = $.param(a);//.replace(/%20/g,'+');
bos@574:
bos@574: if (options.type.toUpperCase() == 'GET') {
bos@574: options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
bos@574: options.data = null; // data is null for 'get'
bos@574: }
bos@574: else
bos@574: options.data = q; // data is the query string for 'post'
bos@574:
bos@574: var $form = this, callbacks = [];
bos@574: if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
bos@574: if (options.clearForm) callbacks.push(function() { $form.clearForm(); });
bos@574:
bos@574: // perform a load on the target only if dataType is not provided
bos@574: if (!options.dataType && options.target) {
bos@574: var oldSuccess = options.success || function(){};
bos@574: callbacks.push(function(data) {
bos@574: if (this.evalScripts)
bos@574: $(options.target).attr("innerHTML", data).evalScripts().each(oldSuccess, arguments);
bos@574: else // jQuery v1.1.4
bos@574: $(options.target).html(data).each(oldSuccess, arguments);
bos@574: });
bos@574: }
bos@574: else if (options.success)
bos@574: callbacks.push(options.success);
bos@574:
bos@574: options.success = function(data, status) {
bos@574: for (var i=0, max=callbacks.length; i < max; i++)
bos@574: callbacks[i](data, status, $form);
bos@574: };
bos@574:
bos@574: // are there files to upload?
bos@574: var files = $('input:file', this).fieldValue();
bos@574: var found = false;
bos@574: for (var j=0; j < files.length; j++)
bos@574: if (files[j])
bos@574: found = true;
bos@574:
bos@574: if (options.iframe || found) // options.iframe allows user to force iframe mode
bos@574: fileUpload();
bos@574: else
bos@574: $.ajax(options);
bos@574:
bos@574: // fire 'notify' event
bos@574: $.event.trigger('form.submit.notify', [this, options]);
bos@574: return this;
bos@574:
bos@574:
bos@574: // private function for handling file uploads (hat tip to YAHOO!)
bos@574: function fileUpload() {
bos@574: var form = $form[0];
bos@574: var opts = $.extend({}, $.ajaxSettings, options);
bos@574:
bos@574: var id = 'jqFormIO' + $.fn.ajaxSubmit.counter++;
bos@574: var $io = $('');
bos@574: var io = $io[0];
bos@574: var op8 = $.browser.opera && window.opera.version() < 9;
bos@574: if ($.browser.msie || op8) io.src = 'javascript:false;document.write("");';
bos@574: $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
bos@574:
bos@574: var xhr = { // mock object
bos@574: responseText: null,
bos@574: responseXML: null,
bos@574: status: 0,
bos@574: statusText: 'n/a',
bos@574: getAllResponseHeaders: function() {},
bos@574: getResponseHeader: function() {},
bos@574: setRequestHeader: function() {}
bos@574: };
bos@574:
bos@574: var g = opts.global;
bos@574: // trigger ajax global events so that activity/block indicators work like normal
bos@574: if (g && ! $.active++) $.event.trigger("ajaxStart");
bos@574: if (g) $.event.trigger("ajaxSend", [xhr, opts]);
bos@574:
bos@574: var cbInvoked = 0;
bos@574: var timedOut = 0;
bos@574:
bos@574: // take a breath so that pending repaints get some cpu time before the upload starts
bos@574: setTimeout(function() {
bos@574: $io.appendTo('body');
bos@574: // jQuery's event binding doesn't work for iframe events in IE
bos@574: io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
bos@574:
bos@574: // make sure form attrs are set
bos@574: var encAttr = form.encoding ? 'encoding' : 'enctype';
bos@574: var t = $form.attr('target');
bos@574: $form.attr({
bos@574: target: id,
bos@574: method: 'POST',
bos@574: action: opts.url
bos@574: });
bos@574: form[encAttr] = 'multipart/form-data';
bos@574:
bos@574: // support timout
bos@574: if (opts.timeout)
bos@574: setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
bos@574:
bos@574: form.submit();
bos@574: $form.attr('target', t); // reset target
bos@574: }, 10);
bos@574:
bos@574: function cb() {
bos@574: if (cbInvoked++) return;
bos@574:
bos@574: io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
bos@574:
bos@574: var ok = true;
bos@574: try {
bos@574: if (timedOut) throw 'timeout';
bos@574: // extract the server response from the iframe
bos@574: var data, doc;
bos@574: doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
bos@574: xhr.responseText = doc.body ? doc.body.innerHTML : null;
bos@574: xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
bos@574:
bos@574: if (opts.dataType == 'json' || opts.dataType == 'script') {
bos@574: var ta = doc.getElementsByTagName('textarea')[0];
bos@574: data = ta ? ta.value : xhr.responseText;
bos@574: if (opts.dataType == 'json')
bos@574: eval("data = " + data);
bos@574: else
bos@574: $.globalEval(data);
bos@574: }
bos@574: else if (opts.dataType == 'xml') {
bos@574: data = xhr.responseXML;
bos@574: if (!data && xhr.responseText != null)
bos@574: data = toXml(xhr.responseText);
bos@574: }
bos@574: else {
bos@574: data = xhr.responseText;
bos@574: }
bos@574: }
bos@574: catch(e){
bos@574: ok = false;
bos@574: $.handleError(opts, xhr, 'error', e);
bos@574: }
bos@574:
bos@574: // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
bos@574: if (ok) {
bos@574: opts.success(data, 'success');
bos@574: if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
bos@574: }
bos@574: if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
bos@574: if (g && ! --$.active) $.event.trigger("ajaxStop");
bos@574: if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
bos@574:
bos@574: // clean up
bos@574: setTimeout(function() {
bos@574: $io.remove();
bos@574: xhr.responseXML = null;
bos@574: }, 100);
bos@574: };
bos@574:
bos@574: function toXml(s, doc) {
bos@574: if (window.ActiveXObject) {
bos@574: doc = new ActiveXObject('Microsoft.XMLDOM');
bos@574: doc.async = 'false';
bos@574: doc.loadXML(s);
bos@574: }
bos@574: else
bos@574: doc = (new DOMParser()).parseFromString(s, 'text/xml');
bos@574: return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
bos@574: };
bos@574: };
bos@574: };
bos@574: $.fn.ajaxSubmit.counter = 0; // used to create unique iframe ids
bos@574:
bos@574: /**
bos@574: * ajaxForm() provides a mechanism for fully automating form submission.
bos@574: *
bos@574: * The advantages of using this method instead of ajaxSubmit() are:
bos@574: *
bos@574: * 1: This method will include coordinates for elements (if the element
bos@574: * is used to submit the form).
bos@574: * 2. This method will include the submit element's name/value data (for the element that was
bos@574: * used to submit the form).
bos@574: * 3. This method binds the submit() method to the form for you.
bos@574: *
bos@574: * Note that for accurate x/y coordinates of image submit elements in all browsers
bos@574: * you need to also use the "dimensions" plugin (this method will auto-detect its presence).
bos@574: *
bos@574: * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
bos@574: * passes the options argument along after properly binding events for submit elements and
bos@574: * the form itself. See ajaxSubmit for a full description of the options argument.
bos@574: *
bos@574: *
bos@574: * @example
bos@574: * var options = {
bos@574: * target: '#myTargetDiv'
bos@574: * };
bos@574: * $('#myForm').ajaxSForm(options);
bos@574: * @desc Bind form's submit event so that 'myTargetDiv' is updated with the server response
bos@574: * when the form is submitted.
bos@574: *
bos@574: *
bos@574: * @example
bos@574: * var options = {
bos@574: * success: function(responseText) {
bos@574: * alert(responseText);
bos@574: * }
bos@574: * };
bos@574: * $('#myForm').ajaxSubmit(options);
bos@574: * @desc Bind form's submit event so that server response is alerted after the form is submitted.
bos@574: *
bos@574: *
bos@574: * @example
bos@574: * var options = {
bos@574: * beforeSubmit: function(formArray, jqForm) {
bos@574: * if (formArray.length == 0) {
bos@574: * alert('Please enter data.');
bos@574: * return false;
bos@574: * }
bos@574: * }
bos@574: * };
bos@574: * $('#myForm').ajaxSubmit(options);
bos@574: * @desc Bind form's submit event so that pre-submit callback is invoked before the form
bos@574: * is submitted.
bos@574: *
bos@574: *
bos@574: * @name ajaxForm
bos@574: * @param options object literal containing options which control the form submission process
bos@574: * @return jQuery
bos@574: * @cat Plugins/Form
bos@574: * @type jQuery
bos@574: */
bos@574: $.fn.ajaxForm = function(options) {
bos@574: return this.ajaxFormUnbind().submit(submitHandler).each(function() {
bos@574: // store options in hash
bos@574: this.formPluginId = $.fn.ajaxForm.counter++;
bos@574: $.fn.ajaxForm.optionHash[this.formPluginId] = options;
bos@574: $(":submit,input:image", this).click(clickHandler);
bos@574: });
bos@574: };
bos@574:
bos@574: $.fn.ajaxForm.counter = 1;
bos@574: $.fn.ajaxForm.optionHash = {};
bos@574:
bos@574: function clickHandler(e) {
bos@574: var $form = this.form;
bos@574: $form.clk = this;
bos@574: if (this.type == 'image') {
bos@574: if (e.offsetX != undefined) {
bos@574: $form.clk_x = e.offsetX;
bos@574: $form.clk_y = e.offsetY;
bos@574: } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
bos@574: var offset = $(this).offset();
bos@574: $form.clk_x = e.pageX - offset.left;
bos@574: $form.clk_y = e.pageY - offset.top;
bos@574: } else {
bos@574: $form.clk_x = e.pageX - this.offsetLeft;
bos@574: $form.clk_y = e.pageY - this.offsetTop;
bos@574: }
bos@574: }
bos@574: // clear form vars
bos@574: setTimeout(function() { $form.clk = $form.clk_x = $form.clk_y = null; }, 10);
bos@574: };
bos@574:
bos@574: function submitHandler() {
bos@574: // retrieve options from hash
bos@574: var id = this.formPluginId;
bos@574: var options = $.fn.ajaxForm.optionHash[id];
bos@574: $(this).ajaxSubmit(options);
bos@574: return false;
bos@574: };
bos@574:
bos@574: /**
bos@574: * ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
bos@574: *
bos@574: * @name ajaxFormUnbind
bos@574: * @return jQuery
bos@574: * @cat Plugins/Form
bos@574: * @type jQuery
bos@574: */
bos@574: $.fn.ajaxFormUnbind = function() {
bos@574: this.unbind('submit', submitHandler);
bos@574: return this.each(function() {
bos@574: $(":submit,input:image", this).unbind('click', clickHandler);
bos@574: });
bos@574:
bos@574: };
bos@574:
bos@574: /**
bos@574: * formToArray() gathers form element data into an array of objects that can
bos@574: * be passed to any of the following ajax functions: $.get, $.post, or load.
bos@574: * Each object in the array has both a 'name' and 'value' property. An example of
bos@574: * an array for a simple login form might be:
bos@574: *
bos@574: * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
bos@574: *
bos@574: * It is this array that is passed to pre-submit callback functions provided to the
bos@574: * ajaxSubmit() and ajaxForm() methods.
bos@574: *
bos@574: * The semantic argument can be used to force form serialization in semantic order.
bos@574: * This is normally true anyway, unless the form contains input elements of type='image'.
bos@574: * If your form must be submitted with name/value pairs in semantic order and your form
bos@574: * contains an input of type='image" then pass true for this arg, otherwise pass false
bos@574: * (or nothing) to avoid the overhead for this logic.
bos@574: *
bos@574: * @example var data = $("#myForm").formToArray();
bos@574: * $.post( "myscript.cgi", data );
bos@574: * @desc Collect all the data from a form and submit it to the server.
bos@574: *
bos@574: * @name formToArray
bos@574: * @param semantic true if serialization must maintain strict semantic ordering of elements (slower)
bos@574: * @type Array