Added 2 of 3 fixes of #164
[jquery.git] / src / ajax / ajax.js
1 jQuery.fn.extend({
2
3         /**
4          * Load HTML from a remote file and inject it into the DOM, only if it's
5          * been modified by the server.
6          *
7          * @example $("#feeds").loadIfModified("feeds.html")
8          * @before <div id="feeds"></div>
9          * @result <div id="feeds"><b>45</b> feeds found.</div>
10          *
11          * @name loadIfModified
12          * @type jQuery
13          * @param String url The URL of the HTML file to load.
14          * @param Hash params A set of key/value pairs that will be sent to the server.
15          * @param Function callback A function to be executed whenever the data is loaded.
16          * @cat AJAX
17          */
18         loadIfModified: function( url, params, callback ) {
19                 this.load( url, params, callback, 1 );
20         },
21
22         /**
23          * Load HTML from a remote file and inject it into the DOM.
24          *
25          * @example $("#feeds").load("feeds.html")
26          * @before <div id="feeds"></div>
27          * @result <div id="feeds"><b>45</b> feeds found.</div>
28          *
29          * @example $("#feeds").load("feeds.html",
30          *   {test: true},
31          *   function() { alert("load is done"); }
32          * );
33          * @desc Same as above, but with an additional parameter
34          * and a callback that is executed when the data was loaded.
35          *
36          * @test stop();
37          * $('#first').load("data/name.php", function() {
38          *      ok( $('#first').text() == 'ERROR', 'Check if content was injected into the DOM' );
39          *      start();
40          * });
41          *
42          * @test stop(); // check if load can be called with only url
43          * $('#first').load("data/name.php");
44          * $.get("data/name.php", function() {
45          *   ok( $('#first').text() == 'ERROR', 'Check if load works without callback');
46          *   start();
47          * });
48          *
49          * @name load
50          * @type jQuery
51          * @param String url The URL of the HTML file to load.
52          * @param Hash params A set of key/value pairs that will be sent to the server.
53          * @param Function callback A function to be executed whenever the data is loaded.
54          * @cat AJAX
55          */
56         load: function( url, params, callback, ifModified ) {
57                 if ( url.constructor == Function )
58                         return this.bind("load", url);
59         
60                 callback = callback || function(){};
61         
62                 // Default to a GET request
63                 var type = "GET";
64         
65                 // If the second parameter was provided
66                 if ( params ) {
67                         // If it's a function
68                         if ( params.constructor == Function ) {
69                                 // We assume that it's the callback
70                                 callback = params;
71                                 params = null;
72                                 
73                         // Otherwise, build a param string
74                         } else {
75                                 params = jQuery.param( params );
76                                 type = "POST";
77                         }
78                 }
79                 
80                 var self = this;
81                 
82                 // Request the remote document
83                 jQuery.ajax( type, url, params,function(res, status){
84                         
85                         if ( status == "success" || !ifModified && status == "notmodified" ) {
86                                 // Inject the HTML into all the matched elements
87                                 self.html(res.responseText).each( callback, [res.responseText, status] );
88                                 
89                                 // Execute all the scripts inside of the newly-injected HTML
90                                 jQuery("script", self).each(function(){
91                                         if ( this.src )
92                                                 jQuery.getScript( this.src );
93                                         else
94                                                 eval.call( window, this.text || this.textContent || this.innerHTML || "" );
95                                 });
96                         } else
97                                 callback.apply( self, [res.responseText, status] );
98         
99                 }, ifModified);
100                 
101                 return this;
102         },
103
104         /**
105          * Serializes a set of input elements into a string of data.
106          * This will serialize all given elements. If you need 
107          * serialization similar to the form submit of a browser,
108          * you should use the form plugin. This is also true for
109          * selects with multiple attribute set, only a single option
110          * is serialized.
111          *
112          * @example $("input[@type=text]").serialize();
113          * @before <input type='text' name='name' value='John'/>
114          * <input type='text' name='location' value='Boston'/>
115          * @after name=John&location=Boston
116          * @desc Serialize a selection of input elements to a string
117          *
118          * @test var data = $(':input').not('button').serialize();
119          * // ignore button, IE takes text content as value, not relevant for this test
120          * ok( data == 'action=Test&text2=Test&radio1=on&radio2=on&check=on&=on&hidden=&foo[bar]=&name=name&=foobar&select1=&select2=3&select3=1', 'Check form serialization as query string' );
121          *
122          * @name serialize
123          * @type String
124          * @cat AJAX
125          */
126         serialize: function() {
127                 return jQuery.param( this );
128         }
129         
130 });
131
132 // If IE is used, create a wrapper for the XMLHttpRequest object
133 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
134         XMLHttpRequest = function(){
135                 return new ActiveXObject(
136                         navigator.userAgent.indexOf("MSIE 5") >= 0 ?
137                         "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
138                 );
139         };
140
141 // Attach a bunch of functions for handling common AJAX events
142
143 /**
144  * Attach a function to be executed whenever an AJAX request begins.
145  *
146  * @example $("#loading").ajaxStart(function(){
147  *   $(this).show();
148  * });
149  * @desc Show a loading message whenever an AJAX request starts.
150  *
151  * @name ajaxStart
152  * @type jQuery
153  * @param Function callback The function to execute.
154  * @cat AJAX
155  */
156  
157 /**
158  * Attach a function to be executed whenever all AJAX requests have ended.
159  *
160  * @example $("#loading").ajaxStop(function(){
161  *   $(this).hide();
162  * });
163  * @desc Hide a loading message after all the AJAX requests have stopped.
164  *
165  * @name ajaxStop
166  * @type jQuery
167  * @param Function callback The function to execute.
168  * @cat AJAX
169  */
170  
171 /**
172  * Attach a function to be executed whenever an AJAX request completes.
173  *
174  * @example $("#msg").ajaxComplete(function(){
175  *   $(this).append("<li>Request Complete.</li>");
176  * });
177  * @desc Show a message when an AJAX request completes.
178  *
179  * @name ajaxComplete
180  * @type jQuery
181  * @param Function callback The function to execute.
182  * @cat AJAX
183  */
184  
185 /**
186  * Attach a function to be executed whenever an AJAX request completes
187  * successfully.
188  *
189  * @example $("#msg").ajaxSuccess(function(){
190  *   $(this).append("<li>Successful Request!</li>");
191  * });
192  * @desc Show a message when an AJAX request completes successfully.
193  *
194  * @name ajaxSuccess
195  * @type jQuery
196  * @param Function callback The function to execute.
197  * @cat AJAX
198  */
199  
200 /**
201  * Attach a function to be executed whenever an AJAX request fails.
202  *
203  * @example $("#msg").ajaxError(function(){
204  *   $(this).append("<li>Error requesting page.</li>");
205  * });
206  * @desc Show a message when an AJAX request fails.
207  *
208  * @name ajaxError
209  * @type jQuery
210  * @param Function callback The function to execute.
211  * @cat AJAX
212  */
213  
214 /**
215  * @test stop(); var counter = { complete: 0, success: 0, error: 0 };
216  * var success = function() { counter.success++ };
217  * var error = function() { counter.error++ };
218  * var complete = function() { counter.complete++ };
219  * $('#foo').ajaxStart(complete).ajaxStop(complete).ajaxComplete(complete).ajaxError(error).ajaxSuccess(success);
220  * // start with successful test
221  * $.ajax({url: "data/name.php", success: success, error: error, complete: function() {
222  *   ok( counter.error == 0, 'Check succesful request' );
223  *   ok( counter.success == 2, 'Check succesful request' );
224  *   ok( counter.complete == 3, 'Check succesful request' );
225  *   counter.error = 0; counter.success = 0; counter.complete = 0;
226  *   $.ajaxTimeout(500);
227  *   $.ajax({url: "data/name.php?wait=5", success: success, error: error, complete: function() {
228  *     ok( counter.error == 2, 'Check failed request' );
229  *     ok( counter.success == 0, 'Check failed request' );
230  *     ok( counter.complete == 3, 'Check failed request' );
231  *     start();
232  *   }});
233  * }});
234  
235  * @test stop(); var counter = { complete: 0, success: 0, error: 0 };
236  * counter.error = 0; counter.success = 0; counter.complete = 0;
237  * var success = function() { counter.success++ };
238  * var error = function() { counter.error++ };
239  * $.ajaxTimeout(0);
240  * $.ajax({url: "data/name.php", global: false, success: success, error: error, complete: function() {
241  *   ok( counter.error == 0, 'Check sucesful request without globals' );
242  *   ok( counter.success == 1, 'Check sucesful request without globals' );
243  *   ok( counter.complete == 0, 'Check sucesful request without globals' );
244  *   counter.error = 0; counter.success = 0; counter.complete = 0;
245  *   $.ajaxTimeout(500);
246  *   $.ajax({url: "data/name.php?wait=5", global: false, success: success, error: error, complete: function() {
247  *      ok( counter.error == 1, 'Check failed request without globals' );
248  *      ok( counter.success == 0, 'Check failed request without globals' );
249  *      ok( counter.complete == 0, 'Check failed request without globals' );
250  *      start();
251  *   }});
252  * }});
253  * 
254  * @name ajaxHandlersTesting
255  * @private
256  */
257  
258
259 new function(){
260         var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(",");
261         
262         for ( var i = 0; i < e.length; i++ ) new function(){
263                 var o = e[i];
264                 jQuery.fn[o] = function(f){
265                         return this.bind(o, f);
266                 };
267         };
268 };
269
270 jQuery.extend({
271
272         /**
273          * Load a remote page using an HTTP GET request. All of the arguments to
274          * the method (except URL) are optional.
275          *
276          * @example $.get("test.cgi")
277          *
278          * @example $.get("test.cgi", { name: "John", time: "2pm" } )
279          *
280          * @example $.get("test.cgi", function(data){
281          *   alert("Data Loaded: " + data);
282          * })
283          *
284          * @example $.get("test.cgi",
285          *   { name: "John", time: "2pm" },
286          *   function(data){
287          *     alert("Data Loaded: " + data);
288          *   }
289          * )
290          *
291          * @test stop();
292          * $.get('data/dashboard.xml', function(xml) {
293          *      var content = [];
294          *      $('tab', xml).each(function() {
295          *              content.push($(this).text());
296          *      });
297          *      ok( content[0] == 'blabla', 'Check first tab');
298          *      ok( content[1] == 'blublu', 'Check second tab');
299          *      start();
300          * });
301          * 
302          *
303          * @name $.get
304          * @type jQuery
305          * @param String url The URL of the page to load.
306          * @param Hash params A set of key/value pairs that will be sent to the server.
307          * @param Function callback A function to be executed whenever the data is loaded.
308          * @cat AJAX
309          */
310         get: function( url, data, callback, type, ifModified ) {
311                 if ( data.constructor == Function ) {
312                         type = callback;
313                         callback = data;
314                         data = null;
315                 }
316                 
317                 // append ? + data or & + data, in case there are already params
318                 if ( data ) url += ((url.indexOf("?") > -1) ? "&" : "?") + jQuery.param(data);
319                 
320                 // Build and start the HTTP Request
321                 jQuery.ajax( "GET", url, null, function(r, status) {
322                         if ( callback ) callback( jQuery.httpData(r,type), status );
323                 }, ifModified);
324         },
325         
326         /**
327          * Load a remote page using an HTTP GET request, only if it hasn't
328          * been modified since it was last retrieved. All of the arguments to
329          * the method (except URL) are optional.
330          *
331          * @example $.getIfModified("test.html")
332          *
333          * @example $.getIfModified("test.html", { name: "John", time: "2pm" } )
334          *
335          * @example $.getIfModified("test.cgi", function(data){
336          *   alert("Data Loaded: " + data);
337          * })
338          *
339          * @example $.getifModified("test.cgi",
340          *   { name: "John", time: "2pm" },
341          *   function(data){
342          *     alert("Data Loaded: " + data);
343          *   }
344          * )
345          *
346          * @test stop();
347          * $.getIfModified("data/name.php", function(msg) {
348          *     ok( msg == 'ERROR', 'Check ifModified' );
349          *     start();
350          * });
351          *
352          * @name $.getIfModified
353          * @type jQuery
354          * @param String url The URL of the page to load.
355          * @param Hash params A set of key/value pairs that will be sent to the server.
356          * @param Function callback A function to be executed whenever the data is loaded.
357          * @cat AJAX
358          */
359         getIfModified: function( url, data, callback, type ) {
360                 jQuery.get(url, data, callback, type, 1);
361         },
362
363         /**
364          * Loads, and executes, a remote JavaScript file using an HTTP GET request.
365          * All of the arguments to the method (except URL) are optional.
366          *
367          * @example $.getScript("test.js")
368          *
369          * @example $.getScript("test.js", function(){
370          *   alert("Script loaded and executed.");
371          * })
372          *
373          * @test stop();
374          * $.getScript("data/test.js", function() {
375          *      ok( foobar == "bar", 'Check if script was evaluated' );
376          *      start();
377          * });
378          *
379          * @name $.getScript
380          * @type jQuery
381          * @param String url The URL of the page to load.
382          * @param Function callback A function to be executed whenever the data is loaded.
383          * @cat AJAX
384          */
385         getScript: function( url, callback ) {
386                 jQuery.get(url, callback, "script");
387         },
388         
389         /**
390          * Load a remote JSON object using an HTTP GET request.
391          * All of the arguments to the method (except URL) are optional.
392          *
393          * @example $.getJSON("test.js", function(json){
394          *   alert("JSON Data: " + json.users[3].name);
395          * })
396          *
397          * @example $.getJSON("test.js",
398          *   { name: "John", time: "2pm" },
399          *   function(json){
400          *     alert("JSON Data: " + json.users[3].name);
401          *   }
402          * )
403          *
404          * @test stop();
405          * $.getJSON("data/json.php", {json: "array"}, function(json) {
406          *   ok( json[0].name == 'John', 'Check JSON: first, name' );
407          *   ok( json[0].age == 21, 'Check JSON: first, age' );
408          *   ok( json[1].name == 'Peter', 'Check JSON: second, name' );
409          *   ok( json[1].age == 25, 'Check JSON: second, age' );
410          *   start();
411          * });
412          * @test stop();
413          * $.getJSON("data/json.php", function(json) {
414          *   ok( json.data.lang == 'en', 'Check JSON: lang' );
415          *   ok( json.data.length == 25, 'Check JSON: length' );
416          *   start();
417          * });
418          *
419          * @name $.getJSON
420          * @type jQuery
421          * @param String url The URL of the page to load.
422          * @param Hash params A set of key/value pairs that will be sent to the server.
423          * @param Function callback A function to be executed whenever the data is loaded.
424          * @cat AJAX
425          */
426         getJSON: function( url, data, callback ) {
427                 if(callback)
428                         jQuery.get(url, data, callback, "json");
429                 else {
430                         jQuery.get(url, data, "json");
431                 }
432         },
433         
434         /**
435          * Load a remote page using an HTTP POST request. All of the arguments to
436          * the method (except URL) are optional.
437          *
438          * @example $.post("test.cgi")
439          *
440          * @example $.post("test.cgi", { name: "John", time: "2pm" } )
441          *
442          * @example $.post("test.cgi", function(data){
443          *   alert("Data Loaded: " + data);
444          * })
445          *
446          * @example $.post("test.cgi",
447          *   { name: "John", time: "2pm" },
448          *   function(data){
449          *     alert("Data Loaded: " + data);
450          *   }
451          * )
452          *
453          * @test stop();
454          * $.post("data/name.php", {xml: "5-2"}, function(xml){
455          *   $('math', xml).each(function() {
456          *          ok( $('calculation', this).text() == '5-2', 'Check for XML' );
457          *          ok( $('result', this).text() == '3', 'Check for XML' );
458          *       });
459          *   start();
460          * });
461          *
462          * @name $.post
463          * @type jQuery
464          * @param String url The URL of the page to load.
465          * @param Hash params A set of key/value pairs that will be sent to the server.
466          * @param Function callback A function to be executed whenever the data is loaded.
467          * @cat AJAX
468          */
469         post: function( url, data, callback, type ) {
470                 // Build and start the HTTP Request
471                 jQuery.ajax( "POST", url, jQuery.param(data), function(r, status) {
472                         if ( callback ) callback( jQuery.httpData(r,type), status );
473                 });
474         },
475         
476         // timeout (ms)
477         timeout: 0,
478
479         /**
480          * Set the timeout of all AJAX requests to a specific amount of time.
481          * This will make all future AJAX requests timeout after a specified amount
482          * of time (the default is no timeout).
483          *
484          * @example $.ajaxTimeout( 5000 );
485          * @desc Make all AJAX requests timeout after 5 seconds.
486          *
487          * @test stop();
488          * var passed = 0;
489          * var timeout;
490          * $.ajaxTimeout(1000);
491          * var pass = function() {
492          *      passed++;
493          *      if(passed == 2) {
494          *              ok( true, 'Check local and global callbacks after timeout' );
495          *              clearTimeout(timeout);
496          *      $('#main').unbind("ajaxError");
497          *              start();
498          *      }
499          * };
500          * var fail = function() {
501          *      ok( false, 'Check for timeout failed' );
502          *      start();
503          * };
504          * timeout = setTimeout(fail, 1500);
505          * $('#main').ajaxError(pass);
506          * $.ajax({
507          *   type: "GET",
508          *   url: "data/name.php?wait=5",
509          *   error: pass,
510          *   success: fail
511          * });
512          *
513          * @test stop(); $.ajaxTimeout(50);
514          * $.ajax({
515          *   type: "GET",
516          *   timeout: 5000,
517          *   url: "data/name.php?wait=1",
518          *   error: function() {
519          *         ok( false, 'Check for local timeout failed' );
520          *         start();
521          *   },
522          *   success: function() {
523          *     ok( true, 'Check for local timeout' );
524          *     start();
525          *   }
526          * });
527          * // reset timeout
528          * $.ajaxTimeout(0);
529          * 
530          *
531          * @name $.ajaxTimeout
532          * @type jQuery
533          * @param Number time How long before an AJAX request times out.
534          * @cat AJAX
535          */
536         ajaxTimeout: function(timeout) {
537                 jQuery.timeout = timeout;
538         },
539
540         // Last-Modified header cache for next request
541         lastModified: {},
542         
543         /**
544          * Load a remote page using an HTTP request. This function is the primary
545          * means of making AJAX requests using jQuery. $.ajax() takes one property,
546          * an object of key/value pairs, that're are used to initalize the request.
547          *
548          * These are all the key/values that can be passed in to 'prop':
549          *
550          * (String) type - The type of request to make (e.g. "POST" or "GET").
551          *
552          * (String) url - The URL of the page to request.
553          * 
554          * (String) data - A string of data to be sent to the server (POST only).
555          *
556          * (String) dataType - The type of data that you're expecting back from
557          * the server (e.g. "xml", "html", "script", or "json").
558          *
559          * (Boolean) ifModified - Allow the request to be successful only if the
560          * response has changed since the last request, default is false, ignoring
561          * the Last-Modified header
562          *
563          * (Number) timeout - Local timeout to override global timeout, eg. to give a
564          * single request a longer timeout while all others timeout after 1 seconds,
565          * see $.ajaxTimeout
566          *
567          * (Boolean) global - Wheather to trigger global AJAX event handlers for
568          * this request, default is true. Set to true to prevent that global handlers
569          * like ajaxStart or ajaxStop are triggered.
570          *
571          * (Function) error - A function to be called if the request fails. The
572          * function gets passed two arguments: The XMLHttpRequest object and a
573          * string describing the type of error that occurred.
574          *
575          * (Function) success - A function to be called if the request succeeds. The
576          * function gets passed one argument: The data returned from the server,
577          * formatted according to the 'dataType' parameter.
578          *
579          * (Function) complete - A function to be called when the request finishes. The
580          * function gets passed two arguments: The XMLHttpRequest object and a
581          * string describing the type the success of the request.
582          *
583          * @example $.ajax({
584          *   type: "GET",
585          *   url: "test.js",
586          *   dataType: "script"
587          * })
588          * @desc Load and execute a JavaScript file.
589          *
590          * @example $.ajax({
591          *   type: "POST",
592          *   url: "some.php",
593          *   data: "name=John&location=Boston",
594          *   success: function(msg){
595          *     alert( "Data Saved: " + msg );
596          *   }
597          * });
598          * @desc Save some data to the server and notify the user once its complete.
599          *
600          * @test stop();
601          * $.ajax({
602          *   type: "GET",
603          *   url: "data/name.php?name=foo",
604          *   success: function(msg){
605          *     ok( msg == 'bar', 'Check for GET' );
606          *     start();
607          *   }
608          * });
609          *
610          * @test stop();
611          * $.ajax({
612          *   type: "POST",
613          *   url: "data/name.php",
614          *   data: "name=peter",
615          *   success: function(msg){
616          *     ok( msg == 'pan', 'Check for POST' );
617          *     start();
618          *   }
619          * });
620          *
621          * @name $.ajax
622          * @type jQuery
623          * @param Hash prop A set of properties to initialize the request with.
624          * @cat AJAX
625          */
626         ajax: function( type, url, data, ret, ifModified ) {
627                 // If only a single argument was passed in,
628                 // assume that it is a object of key/value pairs
629                 if ( !url ) {
630                         ret = type.complete;
631                         var success = type.success;
632                         var error = type.error;
633                         var dataType = type.dataType;
634                         var global = typeof type.global == "boolean" ? type.global : true;
635                         var timeout = typeof type.timeout == "number" ? type.timeout : jQuery.timeout;
636                         var ifModified = type.ifModified || false;
637                         data = type.data;
638                         url = type.url;
639                         type = type.type;
640                 }
641                 
642                 // Watch for a new set of requests
643                 if ( global && ! jQuery.active++ )
644                         jQuery.event.trigger( "ajaxStart" );
645
646                 var requestDone = false;
647         
648                 // Create the request object
649                 var xml = new XMLHttpRequest();
650         
651                 // Open the socket
652                 xml.open(type || "GET", url, true);
653                 
654                 // Set the correct header, if data is being sent
655                 if ( data )
656                         xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
657                 
658                 // Set the If-Modified-Since header, if ifModified mode.
659                 if ( ifModified )
660                         xml.setRequestHeader("If-Modified-Since",
661                                 jQuery.lastModified[url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
662                 
663                 // Set header so the called script knows that it's an XMLHttpRequest
664                 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
665         
666                 // Make sure the browser sends the right content length
667                 if ( xml.overrideMimeType )
668                         xml.setRequestHeader("Connection", "close");
669                 
670                 // Wait for a response to come back
671                 var onreadystatechange = function(istimeout){
672                         // The transfer is complete and the data is available, or the request timed out
673                         if ( xml && (xml.readyState == 4 || istimeout == "timeout") ) {
674                                 requestDone = true;
675
676                                 var status = jQuery.httpSuccess( xml ) && istimeout != "timeout" ?
677                                         ifModified && jQuery.httpNotModified( xml, url ) ? "notmodified" : "success" : "error";
678                                 
679                                 // Make sure that the request was successful or notmodified
680                                 if ( status != "error" ) {
681                                         // Cache Last-Modified header, if ifModified mode.
682                                         var modRes;
683                                         try {
684                                                 modRes = xml.getResponseHeader("Last-Modified");
685                                         } catch(e) {} // swallow exception thrown by FF if header is not available
686                                         
687                                         if ( ifModified && modRes )
688                                                 jQuery.lastModified[url] = modRes;
689                                         
690                                         // If a local callback was specified, fire it
691                                         if ( success )
692                                                 success( jQuery.httpData( xml, dataType ), status );
693                                         
694                                         // Fire the global callback
695                                         if( global )
696                                                 jQuery.event.trigger( "ajaxSuccess" );
697                                 
698                                 // Otherwise, the request was not successful
699                                 } else {
700                                         // If a local callback was specified, fire it
701                                         if ( error ) error( xml, status );
702                                         
703                                         // Fire the global callback
704                                         if( global )
705                                                 jQuery.event.trigger( "ajaxError" );
706                                 }
707                                 
708                                 // The request was completed
709                                 if( global )
710                                         jQuery.event.trigger( "ajaxComplete" );
711                                 
712                                 // Handle the global AJAX counter
713                                 if ( global && ! --jQuery.active )
714                                         jQuery.event.trigger( "ajaxStop" );
715         
716                                 // Process result
717                                 if ( ret ) ret(xml, status);
718                                 
719                                 // Stop memory leaks
720                                 xml.onreadystatechange = function(){};
721                                 xml = null;
722                                 
723                         }
724                 };
725                 xml.onreadystatechange = onreadystatechange;
726                 
727                 // Timeout checker
728                 if(timeout > 0)
729                         setTimeout(function(){
730                                 // Check to see if the request is still happening
731                                 if (xml) {
732                                         // Cancel the request
733                                         xml.abort();
734
735                                         if ( !requestDone ) onreadystatechange( "timeout" );
736
737                                         // Clear from memory
738                                         xml = null;
739                                 }
740                         }, timeout);
741                 
742                 // Send the data
743                 xml.send(data);
744         },
745         
746         // Counter for holding the number of active queries
747         active: 0,
748         
749         // Determines if an XMLHttpRequest was successful or not
750         httpSuccess: function(r) {
751                 try {
752                         return !r.status && location.protocol == "file:" ||
753                                 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
754                                 jQuery.browser.safari && r.status == undefined;
755                 } catch(e){}
756
757                 return false;
758         },
759
760         // Determines if an XMLHttpRequest returns NotModified
761         httpNotModified: function(xml, url) {
762                 try {
763                         var xmlRes = xml.getResponseHeader("Last-Modified");
764
765                         // Firefox always returns 200. check Last-Modified date
766                         return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
767                                 jQuery.browser.safari && xml.status == undefined;
768                 } catch(e){}
769
770                 return false;
771         },
772         
773         /* Get the data out of an XMLHttpRequest.
774          * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
775          * otherwise return plain text.
776          * (String) data - The type of data that you're expecting back,
777          * (e.g. "xml", "html", "script")
778          */
779         httpData: function(r,type) {
780                 var ct = r.getResponseHeader("content-type");
781                 var data = !type && ct && ct.indexOf("xml") >= 0;
782                 data = type == "xml" || data ? r.responseXML : r.responseText;
783
784                 // If the type is "script", eval it
785                 if ( type == "script" ) eval.call( window, data );
786
787                 // Get the JavaScript object, if JSON is used.
788                 if ( type == "json" ) eval( "data = " + data );
789
790                 return data;
791         },
792         
793         // Serialize an array of form elements or a set of
794         // key/values into a query string
795         param: function(a) {
796                 var s = [];
797                 
798                 // If an array was passed in, assume that it is an array
799                 // of form elements
800                 if ( a.constructor == Array || a.jquery ) {
801                         // Serialize the form elements
802                         for ( var i = 0; i < a.length; i++ )
803                                 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
804                         
805                 // Otherwise, assume that it's an object of key/value pairs
806                 } else {
807                         // Serialize the key/values
808                         for ( var j in a )
809                                 s.push( j + "=" + encodeURIComponent( a[j] ) );
810                 }
811                 
812                 // Return the resulting serialization
813                 return s.join("&");
814         }
815
816 });