21a993498c5e2c43220a0bc613e8eaa3e728d1f6
[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(res){
124                 // Assign it and execute all scripts
125                 self.html(res.responseText).find("script").each(function(){
126                         try { eval( this.text || this.textContent || this.innerHTML || ""); } catch(e){}
127                 });
128
129                 // Callback function
130                 if (f && f.constructor == Function)
131                         f(res.responseText);
132         });
133         return this;
134 };
135
136 /**
137  * Initial frontend function to submit form variables. This function
138  * is for registering coordinates, in the case of an image being used
139  * as the submit element, and sets up an event to listen and wait for
140  * a form submit click. It then calls any following chained functions
141  * to actually gather the variables and submit them.
142  *
143  * Usage examples, when used with getForm().putForm():
144  *
145  * 1. Just eval the results returned from the backend.
146  *    $('#form-id').form();
147  *
148  * 2. Render backend results directly to target ID (expects (x)HTML).
149  *    $('#form-id').form('#target-id');
150  *
151  * 3. Submit to backend URL (form action) then call this function.
152  *    $('#form-id').form(post_callback);
153  *
154  * 4. Load target ID with backend results then call a function.
155  *    $('#form-id').form('#target-id', null, post_callback);
156  *
157  * 5. Call a browser function (for validation) and then (optionally)
158  *    load server results to target ID.
159  *    $('#form-id').form('#target-id', pre_callback);
160  *
161  * 6. Call validation function first then load server results to
162  *    target ID and then also call a browser function.
163  *    $('#form-id').form('#target-id', pre_callback, post_callback);
164  *
165  * @param target   arg for the target id element to render
166  * @param pre_cb   callback function before submission
167  * @param post_cb  callback after any results are returned
168  * @return         "this" object
169  * @see            getForm(), putForm()
170  * @author         Mark Constable (markc@renta.net)
171  * @author         G. vd Hoven, Mike Alsup, Sam Collett
172  * @version        20060606
173  */
174 $.fn.form = function(target, pre_cb, post_cb) {
175         $('input[@type="submit"],input[@type="image"]', this).click(function(ev){
176                 this.form.clicked = this;
177                 if (ev.offsetX != undefined) {
178                         this.form.clicked_x = ev.offsetX;
179                         this.form.clicked_y = ev.offsetY;
180                 } else {
181                         this.form.clicked_x = ev.pageX - this.offsetLeft;
182                         this.form.clicked_y = ev.pageY - this.offsetTop;
183                 }
184         });
185         this.submit(function(e){
186                 e.preventDefault();
187                 $(this).getForm().putForm(target, pre_cb, post_cb);
188                 return this;
189   });
190 };
191
192 /**
193  * This function gathers form element variables into an array that
194  * is embedded into the current "this" variable as "this.vars". It
195  * is normally used in conjunction with form() and putForm() but can
196  * be used standalone as long as an image is not used for submission.
197  *
198  * Standalone usage examples:
199  *
200  * 1. Gather form vars and return array to LHS variable.
201  *    var myform = $('#form-id').getForm();
202  *
203  * 2. Provide a serialized URL-ready string (after 1. above).
204  *    var mystring = $.param(myform.vars);
205  *
206  * 3. Gather form vars and send to RHS plugin via "this.vars".
207  *    $('#form-id').getForm().some_other_plugin();
208  *
209  * @return         "this" object
210  * @see            form(), putForm()
211  * @author         Mark Constable (markc@renta.net)
212  * @author         G. vd Hoven, Mike Alsup, Sam Collett
213  * @version        20060606
214  */
215 $.fn.getForm = function() {
216   var a = [];
217   var ok = {INPUT:true, TEXTAREA:true, OPTION:true};
218   $('*', this).each(function() {
219     if (this.disabled || this.type == 'reset' || (this.type == 'checkbox' && !this.checked) || (this.type == 'radio' && !this.checked))
220         return;
221
222     if (this.type == 'submit' || this.type == 'image') {
223       if (this.form.clicked != this)
224         return;
225
226       if (this.type == 'image') {
227         if (this.form.clicked_x) {
228                                         a.push({name: this.name+'_x', value: this.form.clicked_x});
229                                         a.push({name: this.name+'_y', value: this.form.clicked_y});
230                                         return;
231                                 }
232                         }
233                 }
234
235                 if (!ok[this.nodeName.toUpperCase()])
236                         return;
237
238                 var par = this.parentNode;
239                 var p = par.nodeName.toUpperCase();
240                 if ((p == 'SELECT' || p == 'OPTGROUP') && !this.selected)
241                         return;
242
243                 var n = this.name || par.name;
244                 if (!n && p == 'OPTGROUP' && (par = par.parentNode))
245                         n = par.name;
246
247                 if (n == undefined)
248                         return;
249
250                 a.push({name: n, value: this.value});
251         });
252
253         this.vars = a;
254
255         return this;
256 }
257
258 /**
259  * Final form submission plugin usually used in conjunction with
260  * form() and getForm(). If a second argument is a valid function
261  * then it will be called before the form vars are sent to the
262  * backend. If this pre-submit function returns exactly "false"
263  * then it will abort further processing otherwise the process
264  * will continue according to the first and third arguments.
265  *
266  * If the first argument is a function, and it exists, then the form
267  * values will be submitted and that callback function called. If
268  * the first argument is a string value then the "load()" plugin
269  * will be called which will populate the innerHTML of the indicated
270  * element and a callback will be called if there is third argument.
271  * If there are no arguments then the form values are submitted with
272  * an additional variable (evaljs=1) which indicates to the backend
273  * to to prepare the returned results for evaluation, ie; the result
274  * needs to be valid javascript all on a single line.
275  *
276  * Usage example:
277  *
278  * $.fn.myvars = function() {
279  *   this.vars = [];
280  *   for (var i in this) {
281  *     if (this[i] instanceof Function || this[i] == null) continue;
282  *     this.vars.push({name: i, value: this[i].length});
283  *   }
284  *   return this;
285  * }
286  *
287  * precb = function(vars) {
288  *   return confirm('Submit these values?\n\n'+$.param(vars));
289  * }
290  *
291  * $('*').myvars().putForm('#mytarget',precb,null,'myhandler.php');
292  *
293  * @param target   arg for the target id element to render
294  * @param pre_cb   callback function before submission
295  * @param post_cb  callback after any results are returned
296  * @param url      form action override
297  * @param mth      form method override
298  * @return         "this" object
299  * @see            form(), getForm(), load(), xml()
300  * @author         Mark Constable (markc@renta.net)
301  * @author         G. vd Hoven, Mike Alsup, Sam Collett
302  * @version        20060606
303  */
304 $.fn.putForm = function(target, pre_cb, post_cb, url, mth) {
305         if (pre_cb && pre_cb.constructor == Function)
306                 if (pre_cb(this.vars) === false)
307                         return;
308
309         var f = this.get(0);
310         var url = url || f.action || '';
311         var mth = mth || f.method || 'POST';
312
313         if (target && target.constructor == Function) {
314                 $.xml(mth, url, $.param(this.vars), target);
315         } else if (target && target.constructor == String) {
316                 $(target).load(url, this.vars, post_cb);
317         } else {
318                 this.vars.push({name: 'evaljs', value: 1});
319                 $.xml(mth, url, $.param(this.vars), function(r) { eval(r.responseText); });
320         }
321
322         return this;
323 }