/*
* jquery form plugin
* @requires jquery v1.1 or later
*
* examples at: http://malsup.com/jquery/form/
* dual licensed under the mit and gpl licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* revision: $id: jquery.form.js 3028 2007-08-31 13:37:36z joern.zaefferer $
*/
(function($) {
/**
* ajaxsubmit() provides a mechanism for submitting an html form using ajax.
*
* ajaxsubmit accepts a single argument which can be either a success callback function
* or an options object. if a function is provided it will be invoked upon successful
* completion of the submit and will be passed the response from the server.
* if an options object is provided, the following attributes are supported:
*
* target: identifies the element(s) in the page to be updated with the server response.
* this value may be specified as a jquery selection string, a jquery object,
* or a dom element.
* default value: null
*
* url: url to which the form data will be submitted.
* default value: value of form's 'action' attribute
*
* type: the method in which the form data should be submitted, 'get' or 'post'.
* default value: value of form's 'method' attribute (or 'get' if none found)
*
* data: additional data to add to the request, specified as key/value pairs (see $.ajax).
*
* beforesubmit: callback method to be invoked before the form is submitted.
* default value: null
*
* success: callback method to be invoked after the form has been successfully submitted
* and the response has been returned from the server
* default value: null
*
* datatype: expected datatype of the response. one of: null, 'xml', 'script', or 'json'
* default value: null
*
* semantic: boolean flag indicating whether data must be submitted in semantic order (slower).
* default value: false
*
* resetform: boolean flag indicating whether the form should be reset if the submit is successful
*
* clearform: boolean flag indicating whether the form should be cleared if the submit is successful
*
*
* the 'beforesubmit' callback can be provided as a hook for running pre-submit logic or for
* validating the form data. if the 'beforesubmit' callback returns false then the form will
* not be submitted. the 'beforesubmit' callback is invoked with three arguments: the form data
* in array format, the jquery object, and the options object passed into ajaxsubmit.
* the form data array takes the following form:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* if a 'success' callback method is provided it is invoked after the response has been returned
* from the server. it is passed the responsetext or responsexml value (depending on datatype).
* see jquery.ajax for further details.
*
*
* the datatype option provides a means for specifying how the server response should be handled.
* this maps directly to the jquery.httpdata method. the following values are supported:
*
* 'xml': if datatype == 'xml' the server response is treated as xml and the 'success'
* callback method, if specified, will be passed the responsexml value
* 'json': if datatype == 'json' the server response will be evaluted and passed to
* the 'success' callback, if specified
* 'script': if datatype == 'script' the server response is evaluated in the global context
*
*
* note that it does not make sense to use both the 'target' and 'datatype' options. if both
* are provided the target will be ignored.
*
* the semantic argument can be used to force form serialization in semantic order.
* this is normally true anyway, unless the form contains input elements of type='image'.
* if your form must be submitted with name/value pairs in semantic order and your form
* contains an input of type='image" then pass true for this arg, otherwise pass false
* (or nothing) to avoid the overhead for this logic.
*
*
* when used on its own, ajaxsubmit() is typically bound to a form's submit event like this:
*
* $("#form-id").submit(function() {
* $(this).ajaxsubmit(options);
* return false; // cancel conventional submit
* });
*
* when using ajaxform(), however, this is done for you.
*
* @example
* $('#myform').ajaxsubmit(function(data) {
* alert('form submit succeeded! server returned: ' + data);
* });
* @desc submit form and alert server response
*
*
* @example
* var options = {
* target: '#mytargetdiv'
* };
* $('#myform').ajaxsubmit(options);
* @desc submit form and update page element with server response
*
*
* @example
* var options = {
* success: function(responsetext) {
* alert(responsetext);
* }
* };
* $('#myform').ajaxsubmit(options);
* @desc submit form and alert the server response
*
*
* @example
* var options = {
* beforesubmit: function(formarray, jqform) {
* if (formarray.length == 0) {
* alert('please enter data.');
* return false;
* }
* }
* };
* $('#myform').ajaxsubmit(options);
* @desc pre-submit validation which aborts the submit operation if form data is empty
*
*
* @example
* var options = {
* url: myjsonurl.php,
* datatype: 'json',
* success: function(data) {
* // 'data' is an object representing the the evaluated json data
* }
* };
* $('#myform').ajaxsubmit(options);
* @desc json data returned and evaluated
*
*
* @example
* var options = {
* url: myxmlurl.php,
* datatype: 'xml',
* success: function(responsexml) {
* // responsexml is xml document object
* var data = $('myelement', responsexml).text();
* }
* };
* $('#myform').ajaxsubmit(options);
* @desc xml data returned from server
*
*
* @example
* var options = {
* resetform: true
* };
* $('#myform').ajaxsubmit(options);
* @desc submit form and reset it if successful
*
* @example
* $('#myform).submit(function() {
* $(this).ajaxsubmit();
* return false;
* });
* @desc bind form's submit event to use ajaxsubmit
*
*
* @name ajaxsubmit
* @type jquery
* @param options object literal containing options which control the form submission process
* @cat plugins/form
* @return jquery
*/
$.fn.ajaxsubmit = function(options) {
if (typeof options == 'function')
options = { success: options };
options = $.extend({
url: this.attr('action') || window.location,
type: this.attr('method') || 'get'
}, options || {});
// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinymce or fckeditor
var veto = {};
$.event.trigger('form.pre.serialize', [this, options, veto]);
if (veto.veto) return this;
var a = this.formtoarray(options.semantic);
if (options.data) {
for (var n in options.data)
a.push( { name: n, value: options.data[n] } );
}
// give pre-submit callback an opportunity to abort the submit
if (options.beforesubmit && options.beforesubmit(a, this, options) === false) return this;
// fire vetoable 'validate' event
$.event.trigger('form.submit.validate', [a, this, options, veto]);
if (veto.veto) return this;
var q = $.param(a);//.replace(/%20/g,'+');
if (options.type.touppercase() == 'get') {
options.url += (options.url.indexof('?') >= 0 ? '&' : '?') + q;
options.data = null; // data is null for 'get'
}
else
options.data = q; // data is the query string for 'post'
var $form = this, callbacks = [];
if (options.resetform) callbacks.push(function() { $form.resetform(); });
if (options.clearform) callbacks.push(function() { $form.clearform(); });
// perform a load on the target only if datatype is not provided
if (!options.datatype && options.target) {
var oldsuccess = options.success || function(){};
callbacks.push(function(data) {
if (this.evalscripts)
$(options.target).attr("innerhtml", data).evalscripts().each(oldsuccess, arguments);
else // jquery v1.1.4
$(options.target).html(data).each(oldsuccess, arguments);
});
}
else if (options.success)
callbacks.push(options.success);
options.success = function(data, status) {
for (var i=0, max=callbacks.length; i < max; i++)
callbacks[i](data, status, $form);
};
// are there files to upload?
var files = $('input:file', this).fieldvalue();
var found = false;
for (var j=0; j < files.length; j++)
if (files[j])
found = true;
if (options.iframe || found) // options.iframe allows user to force iframe mode
fileupload();
else
$.ajax(options);
// fire 'notify' event
$.event.trigger('form.submit.notify', [this, options]);
return this;
// private function for handling file uploads (hat tip to yahoo!)
function fileupload() {
var form = $form[0];
var opts = $.extend({}, $.ajaxsettings, options);
var id = 'jqformio' + $.fn.ajaxsubmit.counter++;
var $io = $('');
var io = $io[0];
var op8 = $.browser.opera && window.opera.version() < 9;
if ($.browser.msie || op8) io.src = 'javascript:false;document.write("");';
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
var xhr = { // mock object
responsetext: null,
responsexml: null,
status: 0,
statustext: 'n/a',
getallresponseheaders: function() {},
getresponseheader: function() {},
setrequestheader: function() {}
};
var g = opts.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && ! $.active++) $.event.trigger("ajaxstart");
if (g) $.event.trigger("ajaxsend", [xhr, opts]);
var cbinvoked = 0;
var timedout = 0;
// take a breath so that pending repaints get some cpu time before the upload starts
settimeout(function() {
$io.appendto('body');
// jquery's event binding doesn't work for iframe events in ie
io.attachevent ? io.attachevent('onload', cb) : io.addeventlistener('load', cb, false);
// make sure form attrs are set
var encattr = form.encoding ? 'encoding' : 'enctype';
var t = $form.attr('target');
$form.attr({
target: id,
method: 'post',
action: opts.url
});
form[encattr] = 'multipart/form-data';
// support timout
if (opts.timeout)
settimeout(function() { timedout = true; cb(); }, opts.timeout);
form.submit();
$form.attr('target', t); // reset target
}, 10);
function cb() {
if (cbinvoked++) return;
io.detachevent ? io.detachevent('onload', cb) : io.removeeventlistener('load', cb, false);
var ok = true;
try {
if (timedout) throw 'timeout';
// extract the server response from the iframe
var data, doc;
doc = io.contentwindow ? io.contentwindow.document : io.contentdocument ? io.contentdocument : io.document;
xhr.responsetext = doc.body ? doc.body.innerhtml : null;
xhr.responsexml = doc.xmldocument ? doc.xmldocument : doc;
if (opts.datatype == 'json' || opts.datatype == 'script') {
var ta = doc.getelementsbytagname('textarea')[0];
data = ta ? ta.value : xhr.responsetext;
if (opts.datatype == 'json')
eval("data = " + data);
else
$.globaleval(data);
}
else if (opts.datatype == 'xml') {
data = xhr.responsexml;
if (!data && xhr.responsetext != null)
data = toxml(xhr.responsetext);
}
else {
data = xhr.responsetext;
}
}
catch(e){
ok = false;
$.handleerror(opts, xhr, 'error', e);
}
// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (ok) {
opts.success(data, 'success');
if (g) $.event.trigger("ajaxsuccess", [xhr, opts]);
}
if (g) $.event.trigger("ajaxcomplete", [xhr, opts]);
if (g && ! --$.active) $.event.trigger("ajaxstop");
if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
// clean up
settimeout(function() {
$io.remove();
xhr.responsexml = null;
}, 100);
};
function toxml(s, doc) {
if (window.activexobject) {
doc = new activexobject('microsoft.xmldom');
doc.async = 'false';
doc.loadxml(s);
}
else
doc = (new domparser()).parsefromstring(s, 'text/xml');
return (doc && doc.documentelement && doc.documentelement.tagname != 'parsererror') ? doc : null;
};
};
};
$.fn.ajaxsubmit.counter = 0; // used to create unique iframe ids
/**
* 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.
*
* note that for accurate x/y coordinates of image submit elements in all browsers
* you need to also use the "dimensions" plugin (this method will auto-detect its presence).
*
* 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. see ajaxsubmit for a full description of the options argument.
*
*
* @example
* var options = {
* target: '#mytargetdiv'
* };
* $('#myform').ajaxsform(options);
* @desc bind form's submit event so that 'mytargetdiv' is updated with the server response
* when the form is submitted.
*
*
* @example
* var options = {
* success: function(responsetext) {
* alert(responsetext);
* }
* };
* $('#myform').ajaxsubmit(options);
* @desc bind form's submit event so that server response is alerted after the form is submitted.
*
*
* @example
* var options = {
* beforesubmit: function(formarray, jqform) {
* if (formarray.length == 0) {
* alert('please enter data.');
* return false;
* }
* }
* };
* $('#myform').ajaxsubmit(options);
* @desc bind form's submit event so that pre-submit callback is invoked before the form
* is submitted.
*
*
* @name ajaxform
* @param options object literal containing options which control the form submission process
* @return jquery
* @cat plugins/form
* @type jquery
*/
$.fn.ajaxform = function(options) {
return this.ajaxformunbind().submit(submithandler).each(function() {
// store options in hash
this.formpluginid = $.fn.ajaxform.counter++;
$.fn.ajaxform.optionhash[this.formpluginid] = options;
$(":submit,input:image", this).click(clickhandler);
});
};
$.fn.ajaxform.counter = 1;
$.fn.ajaxform.optionhash = {};
function clickhandler(e) {
var $form = this.form;
$form.clk = this;
if (this.type == 'image') {
if (e.offsetx != undefined) {
$form.clk_x = e.offsetx;
$form.clk_y = e.offsety;
} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
var offset = $(this).offset();
$form.clk_x = e.pagex - offset.left;
$form.clk_y = e.pagey - offset.top;
} else {
$form.clk_x = e.pagex - this.offsetleft;
$form.clk_y = e.pagey - this.offsettop;
}
}
// clear form vars
settimeout(function() { $form.clk = $form.clk_x = $form.clk_y = null; }, 10);
};
function submithandler() {
// retrieve options from hash
var id = this.formpluginid;
var options = $.fn.ajaxform.optionhash[id];
$(this).ajaxsubmit(options);
return false;
};
/**
* ajaxformunbind unbinds the event handlers that were bound by ajaxform
*
* @name ajaxformunbind
* @return jquery
* @cat plugins/form
* @type jquery
*/
$.fn.ajaxformunbind = function() {
this.unbind('submit', submithandler);
return this.each(function() {
$(":submit,input:image", this).unbind('click', clickhandler);
});
};
/**
* 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.
* each object in the array has both a 'name' and 'value' property. an example of
* an array for a simple login form might be:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* it is this array that is passed to pre-submit callback functions provided to the
* ajaxsubmit() and ajaxform() methods.
*
* the semantic argument can be used to force form serialization in semantic order.
* this is normally true anyway, unless the form contains input elements of type='image'.
* if your form must be submitted with name/value pairs in semantic order and your form
* contains an input of type='image" then pass true for this arg, otherwise pass false
* (or nothing) to avoid the overhead for this logic.
*
* @example var data = $("#myform").formtoarray();
* $.post( "myscript.cgi", data );
* @desc collect all the data from a form and submit it to the server.
*
* @name formtoarray
* @param semantic true if serialization must maintain strict semantic ordering of elements (slower)
* @type array