Started the form plugin, moving stuff from AJAX over to it.
[jquery.git] / ajax / ajax.js
1 // AJAX Plugin
2 // Docs Here:
3 // http://jquery.com/docs/ajax/
4
5 if ( typeof XMLHttpRequest == 'undefined' && typeof window.ActiveXObject == 'function') {
6         XMLHttpRequest = function() {
7                 return new ActiveXObject((navigator.userAgent.toLowerCase().indexOf('msie 5') >= 0) ?
8                         "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP");
9         };
10 }
11
12 // Counter for holding the active query's
13 $.xmlActive=0;
14
15 $.xml = function( type, url, data, ret ) {
16         if ( !url ) {
17                 ret = type.onComplete;
18                 var onSuccess = type.onSuccess;
19                 var onError = type.onError;
20                 data = type.data;
21                 url = type.url;
22                 type = type.type;
23         }
24
25         var xml = new XMLHttpRequest();
26
27         if ( xml ) {
28                 // Open the socket
29                 xml.open(type || "GET", url, true);
30                 if ( data )
31                         xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
32
33                 // Set header so calling script knows that it's an XMLHttpRequest
34                 xml.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
35
36                 /* Borrowed from Prototype:
37                  * Force "Connection: close" for Mozilla browsers to work around
38                  * a bug where XMLHttpReqeuest sends an incorrect Content-length
39                  * header. See Mozilla Bugzilla #246651.
40                  */
41                 if ( xml.overrideMimeType )
42                         xml.setRequestHeader('Connection', 'close');
43
44                 xml.onreadystatechange = function() {
45                         // Socket is openend
46                         if ( xml.readyState == 1 ) {
47                                 // Increase counter
48                                 $.xmlActive++;
49
50                                 // Show loader if needed
51                                 if ( ($.xmlActive >= 1) && ($.xmlCreate) )
52                                         $.xmlCreate();
53                         }
54
55                         // Socket is closed and data is available
56                         if ( xml.readyState == 4 ) {
57                                 // Decrease counter
58                                 $.xmlActive--;
59
60                                 // Hide loader if needed
61                                 if ( ($.xmlActive <= 0) && ($.xmlDestroy) ) {
62                                         $.xmlDestroy();
63                                         $.xmlActive = 0
64                                 }
65
66                                 if ( ( xml.status && ( xml.status >= 200 && xml.status < 300 ) || xml.status == 304 ) ||
67                                         !xml.status && location.protocol == 'file:' ) {
68                                         if ( onSuccess )
69                                                 onSuccess( xml );
70                                 } else if ( onError ) {
71                                         onError( xml );
72                                 }
73
74                                 // Process result
75                                 if ( ret )
76                                         ret(xml);
77                         }
78                 };
79
80                 xml.send(data)
81         }
82 };
83
84 $.httpData = function(r,type) {
85         return r.getResponseHeader("content-type").indexOf("xml") > 0 || type == "xml" ?
86                 r.responseXML : r.responseText;
87 };
88
89 $.get = function( url, ret, type ) {
90         $.xml( "GET", url, null, function(r) {
91                 if ( ret ) { ret( $.httpData(r,type) ); }
92         });
93 };
94
95 $.getXML = function( url, ret ) {
96         $.get( url, ret, "xml" );
97 };
98
99 $.post = function( url, data, ret, type ) {
100         $.xml( "POST", url, $.param(data), function(r) {
101                 if ( ret ) { ret( $.httpData(r,type) ); }
102         });
103 };
104
105 $.postXML = function( url, data, ret ) {
106         $.post( url, data, ret, "xml" );
107 };
108
109 $.param = function(a) {
110         var s = [];
111         if (a && typeof a == 'object' && a.constructor == Array) {
112                 for ( var i=0; i < a.length; i++ ) {
113                         s[s.length] = a[i].name + "=" + encodeURIComponent( a[i].value );
114                 }
115         } else {
116                 for ( var j in a ) {
117                         s[s.length] = j + "=" + encodeURIComponent( a[j] );
118                 }
119         }
120         return s.join("&");
121 };
122
123 $.fn.load = function(a,o,f) {
124         // Arrrrghhhhhhhh!!
125         // I overwrote the event plugin's .load
126         // this won't happen again, I hope -John
127         if ( a && a.constructor == Function ) {
128                 return this.bind("load", a);
129         }
130
131         var t = "GET";
132         if ( o && o.constructor == Function ) {
133                 f = o;
134                 o = null;
135         }
136         if (typeof o !== 'undefined') {
137                 o = $.param(o);
138                 t = "POST";
139         }
140         var self = this;
141         $.xml(t,a,o,function(res){
142                 // Assign it and execute all scripts
143                 self.html(res.responseText).find("script").each(function(){
144                         try { eval( this.text || this.textContent || this.innerHTML || ""); } catch(e){}
145                 });
146
147                 // Callback function
148                 if (f && f.constructor == Function)
149                         f(res.responseText);
150         });
151         return this;
152 };
153
154 /**
155  * Initial frontend function to submit form variables. This function
156  * is for registering coordinates, in the case of an image being used
157  * as the submit element, and sets up an event to listen and wait for
158  * a form submit click. It then calls any following chained functions
159  * to actually gather the variables and submit them.
160  *
161  * Usage examples, when used with getForm().putForm():
162  *
163  * 1. Just eval the results returned from the backend.
164  *    $('#form-id').form();
165  *
166  * 2. Render backend results directly to target ID (expects (x)HTML).
167  *    $('#form-id').form('#target-id');
168  *
169  * 3. Submit to backend URL (form action) then call this function.
170  *    $('#form-id').form(post_callback);
171  *
172  * 4. Load target ID with backend results then call a function.
173  *    $('#form-id').form('#target-id', null, post_callback);
174  *
175  * 5. Call a browser function (for validation) and then (optionally)
176  *    load server results to target ID.
177  *    $('#form-id').form('#target-id', pre_callback);
178  *
179  * 6. Call validation function first then load server results to
180  *    target ID and then also call a browser function.
181  *    $('#form-id').form('#target-id', pre_callback, post_callback);
182  *
183  * @param target   arg for the target id element to render
184  * @param pre_cb   callback function before submission
185  * @param post_cb  callback after any results are returned
186  * @return         "this" object
187  * @see            getForm(), putForm()
188  * @author         Mark Constable (markc@renta.net)
189  * @author         G. vd Hoven, Mike Alsup, Sam Collett
190  * @version        20060606
191  */
192 $.fn.form = function(target, pre_cb, post_cb) {
193         $('input[@type="submit"],input[@type="image"]', this).click(function(ev){
194                 this.form.clicked = this;
195                 if (ev.offsetX != undefined) {
196                         this.form.clicked_x = ev.offsetX;
197                         this.form.clicked_y = ev.offsetY;
198                 } else {
199                         this.form.clicked_x = ev.pageX - this.offsetLeft;
200                         this.form.clicked_y = ev.pageY - this.offsetTop;
201                 }
202         });
203         this.submit(function(e){
204                 e.preventDefault();
205                 $(this).getForm().putForm(target, pre_cb, post_cb);
206                 return this;
207   });
208 };
209
210 /**
211  * This function gathers form element variables into an array that
212  * is embedded into the current "this" variable as "this.vars". It
213  * is normally used in conjunction with form() and putForm() but can
214  * be used standalone as long as an image is not used for submission.
215  *
216  * Standalone usage examples:
217  *
218  * 1. Gather form vars and return array to LHS variable.
219  *    var myform = $('#form-id').getForm();
220  *
221  * 2. Provide a serialized URL-ready string (after 1. above).
222  *    var mystring = $.param(myform.vars);
223  *
224  * 3. Gather form vars and send to RHS plugin via "this.vars".
225  *    $('#form-id').getForm().some_other_plugin();
226  *
227  * @return         "this" object
228  * @see            form(), putForm()
229  * @author         Mark Constable (markc@renta.net)
230  * @author         G. vd Hoven, Mike Alsup, Sam Collett
231  * @version        20060606
232  */
233 $.fn.getForm = function() {
234   var a = [];
235   var ok = {INPUT:true, TEXTAREA:true, OPTION:true};
236   $('*', this).each(function() {
237     if (this.disabled || this.type == 'reset' || (this.type == 'checkbox' && !this.checked) || (this.type == 'radio' && !this.checked))
238         return;
239
240     if (this.type == 'submit' || this.type == 'image') {
241       if (this.form.clicked != this)
242         return;
243
244       if (this.type == 'image') {
245         if (this.form.clicked_x) {
246                                         a.push({name: this.name+'_x', value: this.form.clicked_x});
247                                         a.push({name: this.name+'_y', value: this.form.clicked_y});
248                                         return;
249                                 }
250                         }
251                 }
252
253                 if (!ok[this.nodeName.toUpperCase()])
254                         return;
255
256                 var par = this.parentNode;
257                 var p = par.nodeName.toUpperCase();
258                 if ((p == 'SELECT' || p == 'OPTGROUP') && !this.selected)
259                         return;
260
261                 var n = this.name || par.name;
262                 if (!n && p == 'OPTGROUP' && (par = par.parentNode))
263                         n = par.name;
264
265                 if (n == undefined)
266                         return;
267
268                 a.push({name: n, value: this.value});
269         });
270
271         this.vars = a;
272
273         return this;
274 }
275
276 /**
277  * Final form submission plugin usually used in conjunction with
278  * form() and getForm(). If a second argument is a valid function
279  * then it will be called before the form vars are sent to the
280  * backend. If this pre-submit function returns exactly "false"
281  * then it will abort further processing otherwise the process
282  * will continue according to the first and third arguments.
283  *
284  * If the first argument is a function, and it exists, then the form
285  * values will be submitted and that callback function called. If
286  * the first argument is a string value then the "load()" plugin
287  * will be called which will populate the innerHTML of the indicated
288  * element and a callback will be called if there is third argument.
289  * If there are no arguments then the form values are submitted with
290  * an additional variable (evaljs=1) which indicates to the backend
291  * to to prepare the returned results for evaluation, ie; the result
292  * needs to be valid javascript all on a single line.
293  *
294  * Usage example:
295  *
296  * $.fn.myvars = function() {
297  *   this.vars = [];
298  *   for (var i in this) {
299  *     if (this[i] instanceof Function || this[i] == null) continue;
300  *     this.vars.push({name: i, value: this[i].length});
301  *   }
302  *   return this;
303  * }
304  *
305  * precb = function(vars) {
306  *   return confirm('Submit these values?\n\n'+$.param(vars));
307  * }
308  *
309  * $('*').myvars().putForm('#mytarget',precb,null,'myhandler.php');
310  *
311  * @param target   arg for the target id element to render
312  * @param pre_cb   callback function before submission
313  * @param post_cb  callback after any results are returned
314  * @param url      form action override
315  * @param mth      form method override
316  * @return         "this" object
317  * @see            form(), getForm(), load(), xml()
318  * @author         Mark Constable (markc@renta.net)
319  * @author         G. vd Hoven, Mike Alsup, Sam Collett
320  * @version        20060606
321  */
322 $.fn.putForm = function(target, pre_cb, post_cb, url, mth) {
323         if (pre_cb && pre_cb.constructor == Function)
324                 if (pre_cb(this.vars) === false)
325                         return;
326
327         var f = this.get(0);
328         var url = url || f.action || '';
329         var mth = mth || f.method || 'POST';
330
331         if (target && target.constructor == Function) {
332                 $.xml(mth, url, $.param(this.vars), target);
333         } else if (target && target.constructor == String) {
334                 $(target).load(url, this.vars, post_cb);
335         } else {
336                 this.vars.push({name: 'evaljs', value: 1});
337                 $.xml(mth, url, $.param(this.vars), function(r) { eval(r.responseText); });
338         }
339
340         return this;
341 }