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