3 * @requires jQuery v1.0.3
\r
5 * Dual licensed under the MIT and GPL licenses:
\r
6 * http://www.opensource.org/licenses/mit-license.php
\r
7 * http://www.gnu.org/licenses/gpl.html
\r
14 * ajaxSubmit() provides a mechanism for submitting an HTML form using AJAX.
\r
16 * ajaxSubmit accepts a single argument which can be either a success callback function
\r
17 * or an options Object. If a function is provided it will be invoked upon successful
\r
18 * completion of the submit and will be passed the response from the server.
\r
19 * If an options Object is provided, the following attributes are supported:
\r
21 * target: Identifies the element(s) in the page to be updated with the server response.
\r
22 * This value may be specified as a jQuery selection string, a jQuery object,
\r
24 * default value: null
\r
26 * url: URL to which the form data will be submitted.
\r
27 * default value: value of form's 'action' attribute
\r
29 * method: @deprecated use 'type'
\r
30 * type: The method in which the form data should be submitted, 'GET' or 'POST'.
\r
31 * default value: value of form's 'method' attribute (or 'GET' if none found)
\r
33 * before: @deprecated use 'beforeSubmit'
\r
34 * beforeSubmit: Callback method to be invoked before the form is submitted.
\r
35 * default value: null
\r
37 * after: @deprecated use 'success'
\r
38 * success: Callback method to be invoked after the form has been successfully submitted
\r
39 * and the response has been returned from the server
\r
40 * default value: null
\r
42 * dataType: Expected dataType of the response. One of: null, 'xml', 'script', or 'json'
\r
43 * default value: null
\r
45 * semantic: Boolean flag indicating whether data must be submitted in semantic order (slower).
\r
46 * default value: false
\r
48 * resetForm: Boolean flag indicating whether the form should be reset if the submit is successful
\r
50 * clearForm: Boolean flag indicating whether the form should be cleared if the submit is successful
\r
53 * The 'beforeSubmit' callback can be provided as a hook for running pre-submit logic or for
\r
54 * validating the form data. If the 'beforeSubmit' callback returns false then the form will
\r
55 * not be submitted. The 'beforeSubmit' callback is invoked with three arguments: the form data
\r
56 * in array format, the jQuery object, and the options object passed into ajaxSubmit.
\r
57 * The form data array takes the following form:
\r
59 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
\r
61 * If a 'success' callback method is provided it is invoked after the response has been returned
\r
62 * from the server. It is passed the responseText or responseXML value (depending on dataType).
\r
63 * See jQuery.ajax for further details.
\r
66 * The dataType option provides a means for specifying how the server response should be handled.
\r
67 * This maps directly to the jQuery.httpData method. The following values are supported:
\r
69 * 'xml': if dataType == 'xml' the server response is treated as XML and the 'after'
\r
70 * callback method, if specified, will be passed the responseXML value
\r
71 * 'json': if dataType == 'json' the server response will be evaluted and passed to
\r
72 * the 'after' callback, if specified
\r
73 * 'script': if dataType == 'script' the server response is evaluated in the global context
\r
76 * Note that it does not make sense to use both the 'target' and 'dataType' options. If both
\r
77 * are provided the target will be ignored.
\r
79 * The semantic argument can be used to force form serialization in semantic order.
\r
80 * This is normally true anyway, unless the form contains input elements of type='image'.
\r
81 * If your form must be submitted with name/value pairs in semantic order and your form
\r
82 * contains an input of type='image" then pass true for this arg, otherwise pass false
\r
83 * (or nothing) to avoid the overhead for this logic.
\r
86 * When used on its own, ajaxSubmit() is typically bound to a form's submit event like this:
\r
88 * $("#form-id").submit(function() {
\r
89 * $(this).ajaxSubmit(options);
\r
90 * return false; // cancel conventional submit
\r
93 * When using ajaxForm(), however, this is done for you.
\r
96 * $('#myForm').ajaxSubmit(function(data) {
\r
97 * alert('Form submit succeeded! Server returned: ' + data);
\r
99 * @desc Submit form and alert server response
\r
104 * target: '#myTargetDiv'
\r
106 * $('#myForm').ajaxSubmit(options);
\r
107 * @desc Submit form and update page element with server response
\r
112 * success: function(responseText) {
\r
113 * alert(responseText);
\r
116 * $('#myForm').ajaxSubmit(options);
\r
117 * @desc Submit form and alert the server response
\r
122 * beforeSubmit: function(formArray, jqForm) {
\r
123 * if (formArray.length == 0) {
\r
124 * alert('Please enter data.');
\r
129 * $('#myForm').ajaxSubmit(options);
\r
130 * @desc Pre-submit validation which aborts the submit operation if form data is empty
\r
135 * url: myJsonUrl.php,
\r
136 * dataType: 'json',
\r
137 * success: function(data) {
\r
138 * // 'data' is an object representing the the evaluated json data
\r
141 * $('#myForm').ajaxSubmit(options);
\r
142 * @desc json data returned and evaluated
\r
147 * url: myXmlUrl.php,
\r
149 * success: function(responseXML) {
\r
150 * // responseXML is XML document object
\r
151 * var data = $('myElement', responseXML).text();
\r
154 * $('#myForm').ajaxSubmit(options);
\r
155 * @desc XML data returned from server
\r
162 * $('#myForm').ajaxSubmit(options);
\r
163 * @desc submit form and reset it if successful
\r
166 * $('#myForm).submit(function() {
\r
167 * $(this).ajaxSubmit();
\r
170 * @desc Bind form's submit event to use ajaxSubmit
\r
175 * @param options object literal containing options which control the form submission process
\r
176 * @cat Plugins/Form
\r
181 * @author jQuery Community
\r
183 jQuery.fn.ajaxSubmit = function(options) {
\r
184 if (typeof options == 'function')
\r
185 options = { success: options };
\r
187 options = jQuery.extend({
\r
188 url: this.attr('action') || '',
\r
189 method: this.attr('method') || 'GET'
\r
192 // remap deprecated options (temporarily)
\r
193 options.success = options.success || options.after;
\r
194 options.beforeSubmit = options.beforeSubmit || options.before;
\r
195 options.type = options.type || options.method;
\r
197 var a = this.formToArray(options.semantic);
\r
199 // give pre-submit callback an opportunity to abort the submit
\r
200 if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) return this;
\r
202 var q = jQuery.param(a);
\r
204 if (options.type.toUpperCase() == 'GET') {
\r
205 // if url already has a '?' then append args after '&'
\r
206 options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
\r
207 options.data = null; // data is null for 'get'
\r
210 options.data = q; // data is the query string for 'post'
\r
212 var $form = this, callbacks = [];
\r
213 if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
\r
214 if (options.clearForm) callbacks.push(function() { $form.clearForm(); });
\r
216 // perform a load on the target only if dataType is not provided
\r
217 if (!options.dataType && options.target) {
\r
218 var oldSuccess = options.success || function(){};
\r
219 callbacks.push(function(data, status) {
\r
220 jQuery(options.target).attr("innerHTML", data).evalScripts().each(oldSuccess, [data, status]);
\r
223 else if (options.success)
\r
224 callbacks.push(options.success);
\r
226 options.success = function(data, status) {
\r
227 for (var i=0, max=callbacks.length; i < max; i++)
\r
228 callbacks[i](data, status);
\r
231 jQuery.ajax(options);
\r
236 * ajaxForm() provides a mechanism for fully automating form submission.
\r
238 * The advantages of using this method instead of ajaxSubmit() are:
\r
240 * 1: This method will include coordinates for <input type="image" /> elements (if the element
\r
241 * is used to submit the form).
\r
242 * 2. This method will include the submit element's name/value data (for the element that was
\r
243 * used to submit the form).
\r
244 * 3. This method binds the submit() method to the form for you.
\r
246 * Note that for accurate x/y coordinates of image submit elements in all browsers
\r
247 * you need to also use the "dimensions" plugin (this method will auto-detect its presence).
\r
249 * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely
\r
250 * passes the options argument along after properly binding events for submit elements and
\r
251 * the form itself. See ajaxSubmit for a full description of the options argument.
\r
256 * target: '#myTargetDiv'
\r
258 * $('#myForm').ajaxSForm(options);
\r
259 * @desc Bind form's submit event so that 'myTargetDiv' is updated with the server response
\r
260 * when the form is submitted.
\r
265 * success: function(responseText) {
\r
266 * alert(responseText);
\r
269 * $('#myForm').ajaxSubmit(options);
\r
270 * @desc Bind form's submit event so that server response is alerted after the form is submitted.
\r
275 * beforeSubmit: function(formArray, jqForm) {
\r
276 * if (formArray.length == 0) {
\r
277 * alert('Please enter data.');
\r
282 * $('#myForm').ajaxSubmit(options);
\r
283 * @desc Bind form's submit event so that pre-submit callback is invoked before the form
\r
288 * @param options object literal containing options which control the form submission process
\r
290 * @cat Plugins/Form
\r
293 * @author jQuery Community
\r
295 jQuery.fn.ajaxForm = function(options) {
\r
296 return this.each(function() {
\r
297 jQuery("input:submit,input:image,button:submit", this).click(function(ev) {
\r
298 var $form = this.form;
\r
300 if (this.type == 'image') {
\r
301 if (ev.offsetX != undefined) {
\r
302 $form.clk_x = ev.offsetX;
\r
303 $form.clk_y = ev.offsetY;
\r
304 } else if (typeof jQuery.fn.offset == 'function') { // try to use dimensions plugin
\r
305 var offset = jQuery(this).offset();
\r
306 $form.clk_x = ev.pageX - offset.left;
\r
307 $form.clk_y = ev.pageY - offset.top;
\r
309 $form.clk_x = ev.pageX - this.offsetLeft;
\r
310 $form.clk_y = ev.pageY - this.offsetTop;
\r
314 setTimeout(function() {
\r
315 $form.clk = $form.clk_x = $form.clk_y = null;
\r
318 }).submit(function(e) {
\r
319 jQuery(this).ajaxSubmit(options);
\r
326 * formToArray() gathers form element data into an array of objects that can
\r
327 * be passed to any of the following ajax functions: $.get, $.post, or load.
\r
328 * Each object in the array has both a 'name' and 'value' property. An example of
\r
329 * an array for a simple login form might be:
\r
331 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
\r
333 * It is this array that is passed to pre-submit callback functions provided to the
\r
334 * ajaxSubmit() and ajaxForm() methods.
\r
336 * The semantic argument can be used to force form serialization in semantic order.
\r
337 * This is normally true anyway, unless the form contains input elements of type='image'.
\r
338 * If your form must be submitted with name/value pairs in semantic order and your form
\r
339 * contains an input of type='image" then pass true for this arg, otherwise pass false
\r
340 * (or nothing) to avoid the overhead for this logic.
\r
342 * @example var data = $("#myForm").formToArray();
\r
343 * $.post( "myscript.cgi", data );
\r
344 * @desc Collect all the data from a form and submit it to the server.
\r
346 * @name formToArray
\r
347 * @param semantic true if serialization must maintain strict semantic ordering of elements (slower)
\r
348 * @type Array<Object>
\r
349 * @cat Plugins/Form
\r
352 * @author jQuery Community
\r
354 jQuery.fn.formToArray = function(semantic) {
\r
356 if (this.length == 0) return a;
\r
358 var form = this[0];
\r
359 var els = semantic ? form.getElementsByTagName('*') : form.elements;
\r
360 if (!els) return a;
\r
361 for(var i=0, max=els.length; i < max; i++) {
\r
366 if (semantic && form.clk && el.type == "image") {
\r
367 // handle image inputs on the fly when semantic == true
\r
368 if(!el.disabled && form.clk == el)
\r
369 a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
\r
372 var v = jQuery.fieldValue(el, true);
\r
373 if (v === null) continue;
\r
374 if (v.constructor == Array) {
\r
375 for(var j=0, jmax=v.length; j < jmax; j++)
\r
376 a.push({name: n, value: v[j]});
\r
379 a.push({name: n, value: v});
\r
382 if (!semantic && form.clk) {
\r
383 // input type=='image' are not found in elements array! handle them here
\r
384 var inputs = form.getElementsByTagName("input");
\r
385 for(var i=0, max=inputs.length; i < max; i++) {
\r
386 var input = inputs[i];
\r
387 var n = input.name;
\r
388 if(n && !input.disabled && input.type == "image" && form.clk == input)
\r
389 a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
\r
397 * Serializes form data into a 'submittable' string. This method will return a string
\r
398 * in the format: name1=value1&name2=value2
\r
400 * The semantic argument can be used to force form serialization in semantic order.
\r
401 * If your form must be submitted with name/value pairs in semantic order then pass
\r
402 * true for this arg, otherwise pass false (or nothing) to avoid the overhead for
\r
403 * this logic (which can be significant for very large forms).
\r
405 * @example var data = $("#myForm").formSerialize();
\r
406 * $.ajax('POST', "myscript.cgi", data);
\r
407 * @desc Collect all the data from a form into a single string
\r
409 * @name formSerialize
\r
410 * @param semantic true if serialization must maintain strict semantic ordering of elements (slower)
\r
412 * @cat Plugins/Form
\r
414 * @author jQuery Community
\r
416 jQuery.fn.formSerialize = function(semantic) {
\r
417 //hand off to jQuery.param for proper encoding
\r
418 return jQuery.param(this.formToArray(semantic));
\r
423 * Serializes all field elements in the jQuery object into a query string.
\r
424 * This method will return a string in the format: name1=value1&name2=value2
\r
426 * The successful argument controls whether or not serialization is limited to
\r
427 * 'successful' controls (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
\r
428 * The default value of the successful argument is true.
\r
430 * @example var data = $("input").formSerialize();
\r
431 * @desc Collect the data from all successful input elements into a query string
\r
433 * @example var data = $(":radio").formSerialize();
\r
434 * @desc Collect the data from all successful radio input elements into a query string
\r
436 * @example var data = $("#myForm :checkbox").formSerialize();
\r
437 * @desc Collect the data from all successful checkbox input elements in myForm into a query string
\r
439 * @example var data = $("#myForm :checkbox").formSerialize(false);
\r
440 * @desc Collect the data from all checkbox elements in myForm (even the unchecked ones) into a query string
\r
442 * @example var data = $(":input").formSerialize();
\r
443 * @desc Collect the data from all successful input, select, textarea and button elements into a query string
\r
445 * @name fieldSerialize
\r
446 * @param successful true if only successful controls should be serialized (default is true)
\r
448 * @cat Plugins/Form
\r
450 jQuery.fn.fieldSerialize = function(successful) {
\r
452 this.each(function() {
\r
455 var v = jQuery.fieldValue(this, successful);
\r
456 if (v && v.constructor == Array) {
\r
457 for (var i=0,max=v.length; i < max; i++)
\r
458 a.push({name: n, value: v[i]});
\r
460 else if (v !== null && typeof v != 'undefined')
\r
461 a.push({name: this.name, value: v});
\r
463 //hand off to jQuery.param for proper encoding
\r
464 return jQuery.param(a);
\r
469 * Returns the value of the field element in the jQuery object. If there is more than one field element
\r
470 * in the jQuery object the value of the first successful one is returned.
\r
472 * The successful argument controls whether or not the field element must be 'successful'
\r
473 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
\r
474 * The default value of the successful argument is true. If this value is false then
\r
475 * the value of the first field element in the jQuery object is returned.
\r
477 * Note: If no valid value can be determined the return value will be undifined.
\r
479 * Note: The fieldValue returned for a select-multiple element or for a checkbox input will
\r
480 * always be an array if it is not undefined.
\r
483 * @example var data = $("#myPasswordElement").formValue();
\r
484 * @desc Gets the current value of the myPasswordElement element
\r
486 * @example var data = $("#myForm :input").formValue();
\r
487 * @desc Get the value of the first successful control in the jQuery object.
\r
489 * @example var data = $("#myForm :checkbox").formValue();
\r
490 * @desc Get the array of values for the first set of successful checkbox controls in the jQuery object.
\r
492 * @example var data = $("#mySingleSelect").formValue();
\r
493 * @desc Get the value of the select control
\r
495 * @example var data = $("#myMultiSelect").formValue();
\r
496 * @desc Get the array of selected values for the select-multiple control
\r
499 * @param Boolean successful true if value returned must be for a successful controls (default is true)
\r
500 * @type String or Array<String>
\r
501 * @cat Plugins/Form
\r
503 jQuery.fn.fieldValue = function(successful) {
\r
506 // loop until we find a value
\r
507 for (var i=0, max=this.length; i < max; i++) {
\r
509 var v = jQuery.fieldValue(el, successful);
\r
510 if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
\r
513 // for checkboxes, consider multiple elements, for everything else just return first valid value
\r
514 if (el.type != 'checkbox') return v;
\r
516 cbName = cbName || el.name;
\r
517 if (cbName != el.name) // return if we hit a checkbox with a different name
\r
519 cbVal = cbVal || [];
\r
526 * Returns the value of the field element.
\r
528 * The successful argument controls whether or not the field element must be 'successful'
\r
529 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
\r
530 * The default value of the successful argument is true. If the given element is not
\r
531 * successful and the successful arg is not false then the returned value will be null.
\r
533 * Note: The fieldValue returned for a select-multiple element will always be an array.
\r
535 * @example var data = jQuery.fieldValue($("#myPasswordElement")[0]);
\r
536 * @desc Gets the current value of the myPasswordElement element
\r
539 * @param Element el The DOM element for which the value will be returned
\r
540 * @param Boolean successful true if value returned must be for a successful controls (default is true)
\r
541 * @type String or Array<String>
\r
542 * @cat Plugins/Form
\r
544 jQuery.fieldValue = function(el, successful) {
\r
545 var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
\r
546 if (typeof successful == 'undefined') successful = true;
\r
548 if (successful && ( !n || el.disabled || t == 'reset' ||
\r
549 (t == 'checkbox' || t == 'radio') && !el.checked ||
\r
550 (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
\r
551 tag == 'select' && el.selectedIndex == -1))
\r
554 if (tag == 'select') {
\r
555 var index = el.selectedIndex;
\r
556 if (index < 0) return null;
\r
557 var a = [], ops = el.options;
\r
558 var one = (t == 'select-one');
\r
559 var max = (one ? index+1 : ops.length);
\r
560 for(var i=(one ? index : 0); i < max; i++) {
\r
563 // extra pain for IE...
\r
564 var v = jQuery.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
\r
576 * Clears the form data. Takes the following actions on the form's input fields:
\r
577 * - input text fields will have their 'value' property set to the empty string
\r
578 * - select elements will have their 'selectedIndex' property set to -1
\r
579 * - checkbox and radio inputs will have their 'checked' property set to false
\r
580 * - inputs of type submit, button, reset, and hidden will *not* be effected
\r
581 * - button elements will *not* be effected
\r
583 * @example $('form').clearForm();
\r
584 * @desc Clears all forms on the page.
\r
588 * @cat Plugins/Form
\r
591 jQuery.fn.clearForm = function() {
\r
592 return this.each(function() {
\r
593 jQuery('input,select,textarea', this).clearFields();
\r
598 * Clears the selected form elements. Takes the following actions on the matched elements:
\r
599 * - input text fields will have their 'value' property set to the empty string
\r
600 * - select elements will have their 'selectedIndex' property set to -1
\r
601 * - checkbox and radio inputs will have their 'checked' property set to false
\r
602 * - inputs of type submit, button, reset, and hidden will *not* be effected
\r
603 * - button elements will *not* be effected
\r
605 * @example $('.myInputs').clearFields();
\r
606 * @desc Clears all inputs with class myInputs
\r
608 * @name clearFields
\r
610 * @cat Plugins/Form
\r
613 jQuery.fn.clearFields = jQuery.fn.clearInputs = function() {
\r
614 return this.each(function() {
\r
615 var t = this.type, tag = this.tagName.toLowerCase();
\r
616 if (t == 'text' || t == 'password' || tag == 'textarea')
\r
618 else if (t == 'checkbox' || t == 'radio')
\r
619 this.checked = false;
\r
620 else if (tag == 'select')
\r
621 this.selectedIndex = -1;
\r
627 * Resets the form data. Causes all form elements to be reset to their original value.
\r
629 * @example $('form').resetForm();
\r
630 * @desc Resets all forms on the page.
\r
634 * @cat Plugins/Form
\r
637 jQuery.fn.resetForm = function() {
\r
638 return this.each(function() {
\r
639 // guard against an input with the name of 'reset'
\r
640 // note that IE reports the reset function as an 'object'
\r
641 if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
\r