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