Did a lot of work on the form plugin. Re-worked the function names, documentation...
authorJohn Resig <jeresig@gmail.com>
Thu, 22 Jun 2006 03:03:44 +0000 (03:03 +0000)
committerJohn Resig <jeresig@gmail.com>
Thu, 22 Jun 2006 03:03:44 +0000 (03:03 +0000)
form/form.js

index 80f0ba2..d1a7ba7 100644 (file)
 /**\r
- * Initial frontend function to submit form variables. This function\r
- * is for registering coordinates, in the case of an image being used\r
- * as the submit element, and sets up an event to listen and wait for\r
- * a form submit click. It then calls any following chained functions\r
- * to actually gather the variables and submit them.\r
+ * A method for submitting an HTML form using AJAX, as opposed to the\r
+ * standard page-load way.\r
  *\r
- * Usage examples, when used with getForm().putForm():\r
+ * This method attempts to mimic the functionality of the original form\r
+ * as best as possible (duplicating the method, action, and exact contents\r
+ * of the form).\r
+ *\r
+ * There are three different resulting operations that can occur, after\r
+ * your form has been submitted.\r
+ *\r
+ * 1. The form is submitted and a callback is fired, letting you know\r
+ *    when it's done:\r
+ *    $("form").ajaxSubmit(function(){\r
+ *      alert("all done!");\r
+ *    });\r
+ *\r
+ * 2. The form is submitted and the resulting HTML contents are injected\r
+ *    into the page, at your specified location.\r
+ *    $("form").ajaxSubmit("#destination");\r
+ *\r
+ * 3. The form is submitted and the results returned from the server are\r
+ *    automatically executed (useful for having the server return more\r
+ *    Javascript commands to execute).\r
+ *    $("form").ajaxSubmit();\r
+ *\r
+ * Additionally, an optional pre-submit callback can be provided. If it,\r
+ * when called with the contents of the form, returns false, the form will\r
+ * not be submitted.\r
+ *\r
+ * Finally, both the URL and method of the form submission can be\r
+ * overidden using the 'url' and 'mth' arguments.\r
+ *\r
+ * @param target   arg for the target id element to render\r
+ * @param post_cb  callback after any results are returned\r
+ * @param pre_cb   callback function before submission\r
+ * @param url      form action override\r
+ * @param mth      form method override\r
+ * @return         "this" object\r
+ * @see            ajaxForm(), serialize(), load(), $.xml()\r
+ * @author         Mark Constable (markc@renta.net)\r
+ * @author         G. vd Hoven, Mike Alsup, Sam Collett, John Resig\r
+ */\r
+$.fn.ajaxSubmit = function(target, post_cb, pre_cb, url, mth) {\r
+       if ( !this.vars ) this.serialize();\r
+       \r
+       if (pre_cb && pre_cb.constructor == Function)\r
+               if (pre_cb(this.vars) === false) return;\r
+\r
+       var f = this.get(0);\r
+       var url = url || f.action || '';\r
+       var mth = mth || f.method || 'POST';\r
+\r
+       if (target && target.constructor == Function) {\r
+               $.xml(mth, url, $.param(this.vars), target);\r
+       } else if (target && target.constructor == String) {\r
+               $(target).load(url, this.vars, post_cb);\r
+       } else {\r
+               this.vars.push({name: 'evaljs', value: 1});\r
+               $.xml(mth, url, $.param(this.vars), function(r) {\r
+                       eval(r.responseText);\r
+               });\r
+       }\r
+\r
+       return this;\r
+};\r
+\r
+/**\r
+ * This function can be used to turn any HTML form into a form\r
+ * that submits using AJAX only.\r
+ *\r
+ * The purpose of using this method, instead of the ajaxSubmit()\r
+ * and submit() methods, is to make absolutely sure that the\r
+ * coordinates of <input type="image"/> elements are transmitted\r
+ * correctly OR figuring out exactly which <input type="submit"/>\r
+ * element was clicked to submit the form.\r
+ *\r
+ * If neither of the above points are important to you, then you'll\r
+ * probably just want to stick with the simpler ajaxSubmit() function.\r
+ *\r
+ * Usage examples, similar to ajaxSubmit():\r
  *\r
  * 1. Just eval the results returned from the backend.\r
- *    $('#form-id').form();\r
+ *    $('#form-id').ajaxForm();\r
  *\r
  * 2. Render backend results directly to target ID (expects (x)HTML).\r
- *    $('#form-id').form('#target-id');\r
+ *    $('#form-id').ajaxForm('#target-id');\r
  *\r
  * 3. Submit to backend URL (form action) then call this function.\r
- *    $('#form-id').form(post_callback);\r
+ *    $('#form-id').ajaxForm(post_callback);\r
  *\r
  * 4. Load target ID with backend results then call a function.\r
- *    $('#form-id').form('#target-id', null, post_callback);\r
+ *    $('#form-id').ajaxForm('#target-id', post_callback);\r
  *\r
  * 5. Call a browser function (for validation) and then (optionally)\r
  *    load server results to target ID.\r
- *    $('#form-id').form('#target-id', pre_callback);\r
+ *    $('#form-id').ajaxForm('#target-id', null, pre_callback);\r
  *\r
  * 6. Call validation function first then load server results to\r
  *    target ID and then also call a browser function.\r
- *    $('#form-id').form('#target-id', pre_callback, post_callback);\r
+ *    $('#form-id').ajaxForm('#target-id', post_callback, pre_callback);\r
  *\r
  * @param target   arg for the target id element to render\r
- * @param pre_cb   callback function before submission\r
  * @param post_cb  callback after any results are returned\r
- * @return         "this" object\r
- * @see            getForm(), putForm()\r
+ * @param pre_cb   callback function before submission\r
+ * @return         the jQuery Object\r
+ * @see            serialize(), ajaxSubmit()\r
  * @author         Mark Constable (markc@renta.net)\r
- * @author         G. vd Hoven, Mike Alsup, Sam Collett\r
- * @version        20060606\r
+ * @author         G. vd Hoven, Mike Alsup, Sam Collett, John Resig\r
  */\r
-$.fn.form = function(target, pre_cb, post_cb) {\r
-       $('input[@type="submit"],input[@type="image"]', this).click(function(ev){\r
-               this.form.clicked = this;\r
-               if (ev.offsetX != undefined) {\r
-                       this.form.clicked_x = ev.offsetX;\r
-                       this.form.clicked_y = ev.offsetY;\r
-               } else {\r
-                       this.form.clicked_x = ev.pageX - this.offsetLeft;\r
-                       this.form.clicked_y = ev.pageY - this.offsetTop;\r
-               }\r
-       });\r
-       this.submit(function(e){\r
+$.fn.ajaxForm = function(target, post_cb, pre_cb) {\r
+       return this.each(function(){\r
+               $('input[@type="submit"],input[@type="image"]', this).click(function(ev){\r
+                       this.form.clicked = this;\r
+                       if (ev.offsetX != undefined) {\r
+                               this.form.clicked_x = ev.offsetX;\r
+                               this.form.clicked_y = ev.offsetY;\r
+                       } else {\r
+                               this.form.clicked_x = ev.pageX - this.offsetLeft;\r
+                               this.form.clicked_y = ev.pageY - this.offsetTop;\r
+                       }\r
+               });\r
+       }).submit(function(e){\r
                e.preventDefault();\r
-               $(this).getForm().putForm(target, pre_cb, post_cb);\r
-               return this;\r
+               $(this).ajaxSubmit(target, post_cb, pre_cb);\r
+               return false;\r
        });\r
 };\r
 \r
 /**\r
+ * A simple wrapper function that sits around the .serialize()\r
+ * method, allowing you to easily extract the data stored within\r
+ * a form.\r
+ *\r
+ * Usage examples:\r
+ *\r
+ * 1. Serialize the contents of a form to a & and = delmited string:\r
+ *    $.param( $("form").formdata() );\r
+ *\r
+ * @return         An array of name/value pairs representing the form\r
+ * @see            serialize()\r
+ # @author         John Resig\r
+ */\r
+$.fn.formdata = function(){\r
+       this.serialize();\r
+       return this.vars;\r
+};\r
+\r
+/**\r
  * This function gathers form element variables into an array that\r
  * is embedded into the current "this" variable as "this.vars". It\r
- * is normally used in conjunction with form() and putForm() but can\r
- * be used standalone as long as an image is not used for submission.\r
+ * is normally used in conjunction with formdata() or ajaxSubmit() but can\r
+ * be used standalone as long as you don't need the x and y coordinates\r
+ * associated with an <input type="image"/> element..\r
  *\r
  * Standalone usage examples:\r
  *\r
  * 1. Gather form vars and return array to LHS variable.\r
- *    var myform = $('#form-id').getForm();\r
+ *    var myform = $('#form-id').serialize();\r
  *\r
  * 2. Provide a serialized URL-ready string (after 1. above).\r
  *    var mystring = $.param(myform.vars);\r
  *\r
  * 3. Gather form vars and send to RHS plugin via "this.vars".\r
- *    $('#form-id').getForm().some_other_plugin();\r
+ *    $('#form-id').serialize().some_other_plugin();\r
  *\r
- * @return         "this" object\r
- * @see            form(), putForm()\r
+ * @return         the jQuery Object\r
+ * @see            ajaxForm(), ajaxSubmit()\r
  * @author         Mark Constable (markc@renta.net)\r
- * @author         G. vd Hoven, Mike Alsup, Sam Collett\r
- * @version        20060606\r
+ * @author         G. vd Hoven, Mike Alsup, Sam Collett, John Resig\r
  */\r
-$.fn.getForm = function() {\r
+$.fn.serialize = function() {\r
        var a = [];\r
        var ok = {INPUT:true, TEXTAREA:true, OPTION:true};\r
 \r
        $('*', this).each(function() {\r
-               if (this.disabled || this.type == 'reset' || (this.type == 'checkbox' && !this.checked) || (this.type == 'radio' && !this.checked))\r
-                       return;\r
+               if (this.disabled || this.type == 'reset' || \r
+                       (this.type == 'checkbox' && !this.checked) || \r
+                       (this.type == 'radio' && !this.checked)) return;\r
 \r
                if (this.type == 'submit' || this.type == 'image') {\r
-                       if (this.form.clicked != this)\r
-                               return;\r
+                       if (this.form.clicked != this) return;\r
 \r
                        if (this.type == 'image') {\r
                                if (this.form.clicked_x) {\r
-                                               a.push({name: this.name+'_x', value: this.form.clicked_x});\r
-                                               a.push({name: this.name+'_y', value: this.form.clicked_y});\r
-                                               return;\r
-                                       }\r
+                                       a.push({name: this.name+'_x', value: this.form.clicked_x});\r
+                                       a.push({name: this.name+'_y', value: this.form.clicked_y});\r
+                                       return;\r
                                }\r
+                       }\r
                }\r
 \r
                if (!ok[this.nodeName.toUpperCase()])\r
@@ -103,87 +195,18 @@ $.fn.getForm = function() {
 \r
                var par = this.parentNode;\r
                var p = par.nodeName.toUpperCase();\r
-               if ((p == 'SELECT' || p == 'OPTGROUP') && !this.selected)\r
-                       return;\r
+               if ((p == 'SELECT' || p == 'OPTGROUP') && !this.selected) return;\r
 \r
                var n = this.name || par.name;\r
                if (!n && p == 'OPTGROUP' && (par = par.parentNode))\r
                        n = par.name;\r
 \r
-               if (n == undefined)\r
-                       return;\r
+               if (n == undefined) return;\r
 \r
                a.push({name: n, value: this.value});\r
        });\r
-\r
+       \r
        this.vars = a;\r
 \r
        return this;\r
-}\r
-\r
-/**\r
- * Final form submission plugin usually used in conjunction with\r
- * form() and getForm(). If a second argument is a valid function\r
- * then it will be called before the form vars are sent to the\r
- * backend. If this pre-submit function returns exactly "false"\r
- * then it will abort further processing otherwise the process\r
- * will continue according to the first and third arguments.\r
- *\r
- * If the first argument is a function, and it exists, then the form\r
- * values will be submitted and that callback function called. If\r
- * the first argument is a string value then the "load()" plugin\r
- * will be called which will populate the innerHTML of the indicated\r
- * element and a callback will be called if there is third argument.\r
- * If there are no arguments then the form values are submitted with\r
- * an additional variable (evaljs=1) which indicates to the backend\r
- * to to prepare the returned results for evaluation, ie; the result\r
- * needs to be valid javascript all on a single line.\r
- *\r
- * Usage example:\r
- *\r
- * $.fn.myvars = function() {\r
- *   this.vars = [];\r
- *   for (var i in this) {\r
- *     if (this[i] instanceof Function || this[i] == null) continue;\r
- *     this.vars.push({name: i, value: this[i].length});\r
- *   }\r
- *   return this;\r
- * }\r
- *\r
- * precb = function(vars) {\r
- *   return confirm('Submit these values?\n\n'+$.param(vars));\r
- * }\r
- *\r
- * $('*').myvars().putForm('#mytarget',precb,null,'myhandler.php');\r
- *\r
- * @param target   arg for the target id element to render\r
- * @param pre_cb   callback function before submission\r
- * @param post_cb  callback after any results are returned\r
- * @param url      form action override\r
- * @param mth      form method override\r
- * @return         "this" object\r
- * @see            form(), getForm(), load(), xml()\r
- * @author         Mark Constable (markc@renta.net)\r
- * @author         G. vd Hoven, Mike Alsup, Sam Collett\r
- * @version        20060606\r
- */\r
-$.fn.putForm = function(target, pre_cb, post_cb, url, mth) {\r
-       if (pre_cb && pre_cb.constructor == Function)\r
-               if (pre_cb(this.vars) === false)\r
-                       return;\r
-\r
-       var f = this.get(0);\r
-       var url = url || f.action || '';\r
-       var mth = mth || f.method || 'POST';\r
-\r
-       if (target && target.constructor == Function) {\r
-               $.xml(mth, url, $.param(this.vars), target);\r
-       } else if (target && target.constructor == String) {\r
-               $(target).load(url, this.vars, post_cb);\r
-       } else {\r
-               this.vars.push({name: 'evaljs', value: 1});\r
-               $.xml(mth, url, $.param(this.vars), function(r) { eval(r.responseText); });\r
-       }\r
-\r
-       return this;\r
-}\r
+};\r