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