795cd8a9e0f6526dd162296b1c7a5e07daed64dd
[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 Map params (optional) Key/value pairs that will be sent to the server.
15          * @param Function callback (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).
16          * @cat Ajax
17          */
18         // DEPRECATED
19         loadIfModified: function( url, params, callback ) {
20                 this.load( url, params, callback, 1 );
21         },
22
23         /**
24          * Load HTML from a remote file and inject it into the DOM.
25          *
26          * Note: Avoid to use this to load scripts, instead use $.getScript.
27          * IE strips script tags when there aren't any other characters in front of it.
28          *
29          * @example $("#feeds").load("feeds.html");
30          * @before <div id="feeds"></div>
31          * @result <div id="feeds"><b>45</b> feeds found.</div>
32          *
33          * @example $("#feeds").load("feeds.html",
34          *   {limit: 25},
35          *   function() { alert("The last 25 entries in the feed have been loaded"); }
36          * );
37          * @desc Same as above, but with an additional parameter
38          * and a callback that is executed when the data was loaded.
39          *
40          * @name load
41          * @type jQuery
42          * @param String url The URL of the HTML file to load.
43          * @param Object params (optional) A set of key/value pairs that will be sent as data to the server.
44          * @param Function callback (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).
45          * @cat Ajax
46          */
47         load: function( url, params, callback, ifModified ) {
48                 if ( jQuery.isFunction( url ) )
49                         return this.bind("load", url);
50
51                 var off = url.indexOf(" ");
52                 var selector = url.slice(off, url.length);
53                 url = url.slice(0, off);
54
55                 callback = callback || function(){};
56
57                 // Default to a GET request
58                 var type = "GET";
59
60                 // If the second parameter was provided
61                 if ( params )
62                         // If it's a function
63                         if ( jQuery.isFunction( params ) ) {
64                                 // We assume that it's the callback
65                                 callback = params;
66                                 params = null;
67
68                         // Otherwise, build a param string
69                         } else {
70                                 params = jQuery.param( params );
71                                 type = "POST";
72                         }
73
74                 var self = this;
75
76                 // Request the remote document
77                 jQuery.ajax({
78                         url: url,
79                         type: type,
80                         data: params,
81                         ifModified: ifModified,
82                         complete: function(res, status){
83                                 // If successful, inject the HTML into all the matched elements
84                                 if ( status == "success" || !ifModified && status == "notmodified" )
85                                         // See if a selector was specified
86                                         self.html( selector ?
87                                                 // Create a dummy div to hold the results
88                                                 jQuery("<div/>")
89                                                         // inject the contents of the document in, removing the scripts
90                                                         // to avoid any 'Permission Denied' errors in IE
91                                                         .append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
92
93                                                         // Locate the specified elements
94                                                         .find(selector) :
95
96                                                 // If not, just inject the full result
97                                                 res.responseText );
98
99                                 // Add delay to account for Safari's delay in globalEval
100                                 setTimeout(function(){
101                                         self.each( callback, [res.responseText, status, res] );
102                                 }, 13);
103                         }
104                 });
105                 return this;
106         },
107
108         /**
109          * Serializes a set of input elements into a string of data.
110          * This will serialize all given elements.
111          *
112          * A serialization similar to the form submit of a browser is
113          * provided by the [http://www.malsup.com/jquery/form/ Form Plugin].
114          * It also takes multiple-selects 
115          * into account, while this method recognizes only a single option.
116          *
117          * @example $("input[@type=text]").serialize();
118          * @before <input type='text' name='name' value='John'/>
119          * <input type='text' name='location' value='Boston'/>
120          * @after name=John&amp;location=Boston
121          * @desc Serialize a selection of input elements to a string
122          *
123          * @name serialize
124          * @type String
125          * @cat Ajax
126          */
127         serialize: function() {
128                 return jQuery.param( this );
129         },
130
131         // DEPRECATED
132         // This method no longer does anything - all script evaluation is
133         // taken care of within the HTML injection methods.
134         evalScripts: function(){}
135
136 });
137
138 // Attach a bunch of functions for handling common AJAX events
139
140 /**
141  * Attach a function to be executed whenever an AJAX request begins
142  * and there is none already active.
143  *
144  * @example $("#loading").ajaxStart(function(){
145  *   $(this).show();
146  * });
147  * @desc Show a loading message whenever an AJAX request starts
148  * (and none is already active).
149  *
150  * @name ajaxStart
151  * @type jQuery
152  * @param Function callback The function to execute.
153  * @cat Ajax
154  */
155
156 /**
157  * Attach a function to be executed whenever all AJAX requests have ended.
158  *
159  * @example $("#loading").ajaxStop(function(){
160  *   $(this).hide();
161  * });
162  * @desc Hide a loading message after all the AJAX requests have stopped.
163  *
164  * @name ajaxStop
165  * @type jQuery
166  * @param Function callback The function to execute.
167  * @cat Ajax
168  */
169
170 /**
171  * Attach a function to be executed whenever an AJAX request completes.
172  *
173  * The XMLHttpRequest and settings used for that request are passed
174  * as arguments to the callback.
175  *
176  * @example $("#msg").ajaxComplete(function(request, settings){
177  *   $(this).append("<li>Request Complete.</li>");
178  * });
179  * @desc Show a message when an AJAX request completes.
180  *
181  * @name ajaxComplete
182  * @type jQuery
183  * @param Function callback The function to execute.
184  * @cat Ajax
185  */
186
187 /**
188  * Attach a function to be executed whenever an AJAX request completes
189  * successfully.
190  *
191  * The XMLHttpRequest and settings used for that request are passed
192  * as arguments to the callback.
193  *
194  * @example $("#msg").ajaxSuccess(function(request, settings){
195  *   $(this).append("<li>Successful Request!</li>");
196  * });
197  * @desc Show a message when an AJAX request completes successfully.
198  *
199  * @name ajaxSuccess
200  * @type jQuery
201  * @param Function callback The function to execute.
202  * @cat Ajax
203  */
204
205 /**
206  * Attach a function to be executed whenever an AJAX request fails.
207  *
208  * The XMLHttpRequest and settings used for that request are passed
209  * as arguments to the callback. A third argument, an exception object,
210  * is passed if an exception occured while processing the request.
211  *
212  * @example $("#msg").ajaxError(function(request, settings){
213  *   $(this).append("<li>Error requesting page " + settings.url + "</li>");
214  * });
215  * @desc Show a message when an AJAX request fails.
216  *
217  * @name ajaxError
218  * @type jQuery
219  * @param Function callback The function to execute.
220  * @cat Ajax
221  */
222  
223 /**
224  * Attach a function to be executed before an AJAX request is sent.
225  *
226  * The XMLHttpRequest and settings used for that request are passed
227  * as arguments to the callback.
228  *
229  * @example $("#msg").ajaxSend(function(request, settings){
230  *   $(this).append("<li>Starting request at " + settings.url + "</li>");
231  * });
232  * @desc Show a message before an AJAX request is sent.
233  *
234  * @name ajaxSend
235  * @type jQuery
236  * @param Function callback The function to execute.
237  * @cat Ajax
238  */
239 jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
240         jQuery.fn[o] = function(f){
241                 return this.bind(o, f);
242         };
243 });
244
245 jQuery.extend({
246
247         /**
248          * Load a remote page using an HTTP GET request.
249          *
250          * This is an easy way to send a simple GET request to a server
251          * without having to use the more complex $.ajax function. It
252          * allows a single callback function to be specified that will
253          * be executed when the request is complete (and only if the response
254          * has a successful response code). If you need to have both error
255          * and success callbacks, you may want to use $.ajax.
256          *
257          * @example $.get("test.cgi");
258          *
259          * @example $.get("test.cgi", { name: "John", time: "2pm" } );
260          *
261          * @example $.get("test.cgi", function(data){
262          *   alert("Data Loaded: " + data);
263          * });
264          *
265          * @example $.get("test.cgi",
266          *   { name: "John", time: "2pm" },
267          *   function(data){
268          *     alert("Data Loaded: " + data);
269          *   }
270          * );
271          *
272          * @name $.get
273          * @type XMLHttpRequest
274          * @param String url The URL of the page to load.
275          * @param Map params (optional) Key/value pairs that will be sent to the server.
276          * @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
277          * @cat Ajax
278          */
279         get: function( url, data, callback, type, ifModified ) {
280                 // shift arguments if data argument was ommited
281                 if ( jQuery.isFunction( data ) ) {
282                         callback = data;
283                         data = null;
284                 }
285                 
286                 return jQuery.ajax({
287                         type: "GET",
288                         url: url,
289                         data: data,
290                         success: callback,
291                         dataType: type,
292                         ifModified: ifModified
293                 });
294         },
295
296         /**
297          * Load a remote page using an HTTP GET request, only if it hasn't
298          * been modified since it was last retrieved.
299          *
300          * @example $.getIfModified("test.html");
301          *
302          * @example $.getIfModified("test.html", { name: "John", time: "2pm" } );
303          *
304          * @example $.getIfModified("test.cgi", function(data){
305          *   alert("Data Loaded: " + data);
306          * });
307          *
308          * @example $.getifModified("test.cgi",
309          *   { name: "John", time: "2pm" },
310          *   function(data){
311          *     alert("Data Loaded: " + data);
312          *   }
313          * );
314          *
315          * @name $.getIfModified
316          * @type XMLHttpRequest
317          * @param String url The URL of the page to load.
318          * @param Map params (optional) Key/value pairs that will be sent to the server.
319          * @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
320          * @cat Ajax
321          */
322         // DEPRECATED
323         getIfModified: function( url, data, callback, type ) {
324                 return jQuery.get(url, data, callback, type, 1);
325         },
326
327         /**
328          * Loads, and executes, a remote JavaScript file using an HTTP GET request.
329          *
330          * Warning: Safari <= 2.0.x is unable to evaluate scripts in a global
331          * context synchronously. If you load functions via getScript, make sure
332          * to call them after a delay.
333          *
334          * @example $.getScript("test.js");
335          *
336          * @example $.getScript("test.js", function(){
337          *   alert("Script loaded and executed.");
338          * });
339          *
340          * @name $.getScript
341          * @type XMLHttpRequest
342          * @param String url The URL of the page to load.
343          * @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
344          * @cat Ajax
345          */
346         getScript: function( url, callback ) {
347                 return jQuery.get(url, null, callback, "script");
348         },
349
350         /**
351          * Load JSON data using an HTTP GET request.
352          *
353          * @example $.getJSON("test.js", function(json){
354          *   alert("JSON Data: " + json.users[3].name);
355          * });
356          *
357          * @example $.getJSON("test.js",
358          *   { name: "John", time: "2pm" },
359          *   function(json){
360          *     alert("JSON Data: " + json.users[3].name);
361          *   }
362          * );
363          *
364          * @name $.getJSON
365          * @type XMLHttpRequest
366          * @param String url The URL of the page to load.
367          * @param Map params (optional) Key/value pairs that will be sent to the server.
368          * @param Function callback A function to be executed whenever the data is loaded successfully.
369          * @cat Ajax
370          */
371         getJSON: function( url, data, callback ) {
372                 return jQuery.get(url, data, callback, "json");
373         },
374
375         /**
376          * Load a remote page using an HTTP POST request.
377          *
378          * @example $.post("test.cgi");
379          *
380          * @example $.post("test.cgi", { name: "John", time: "2pm" } );
381          *
382          * @example $.post("test.cgi", function(data){
383          *   alert("Data Loaded: " + data);
384          * });
385          *
386          * @example $.post("test.cgi",
387          *   { name: "John", time: "2pm" },
388          *   function(data){
389          *     alert("Data Loaded: " + data);
390          *   }
391          * );
392          *
393          * @name $.post
394          * @type XMLHttpRequest
395          * @param String url The URL of the page to load.
396          * @param Map params (optional) Key/value pairs that will be sent to the server.
397          * @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
398          * @cat Ajax
399          */
400         post: function( url, data, callback, type ) {
401                 if ( jQuery.isFunction( data ) ) {
402                         callback = data;
403                         data = {};
404                 }
405
406                 return jQuery.ajax({
407                         type: "POST",
408                         url: url,
409                         data: data,
410                         success: callback,
411                         dataType: type
412                 });
413         },
414
415         /**
416          * Set the timeout in milliseconds of all AJAX requests to a specific amount of time.
417          * This will make all future AJAX requests timeout after a specified amount
418          * of time.
419          *
420          * Set to null or 0 to disable timeouts (default).
421          *
422          * You can manually abort requests with the XMLHttpRequest's (returned by
423          * all ajax functions) abort() method.
424          *
425          * Deprecated. Use $.ajaxSetup instead.
426          *
427          * @example $.ajaxTimeout( 5000 );
428          * @desc Make all AJAX requests timeout after 5 seconds.
429          *
430          * @name $.ajaxTimeout
431          * @type undefined
432          * @param Number time How long before an AJAX request times out, in milliseconds.
433          * @cat Ajax
434          */
435         // DEPRECATED
436         ajaxTimeout: function( timeout ) {
437                 jQuery.ajaxSettings.timeout = timeout;
438         },
439         
440         /**
441          * Setup global settings for AJAX requests.
442          *
443          * See $.ajax for a description of all available options.
444          *
445          * @example $.ajaxSetup( {
446          *   url: "/xmlhttp/",
447          *   global: false,
448          *   type: "POST"
449          * } );
450          * $.ajax({ data: myData });
451          * @desc Sets the defaults for AJAX requests to the url "/xmlhttp/",
452          * disables global handlers and uses POST instead of GET. The following
453          * AJAX requests then sends some data without having to set anything else.
454          *
455          * @name $.ajaxSetup
456          * @type undefined
457          * @param Map settings Key/value pairs to use for all AJAX requests
458          * @cat Ajax
459          */
460         ajaxSetup: function( settings ) {
461                 jQuery.extend( jQuery.ajaxSettings, settings );
462         },
463
464         ajaxSettings: {
465                 global: true,
466                 type: "GET",
467                 timeout: 0,
468                 contentType: "application/x-www-form-urlencoded",
469                 processData: true,
470                 async: true,
471                 data: null
472         },
473         
474         // Last-Modified header cache for next request
475         lastModified: {},
476
477         /**
478          * Load a remote page using an HTTP request.
479          *
480          * This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for
481          * higher-level abstractions that are often easier to understand and use,
482          * but don't offer as much functionality (such as error callbacks).
483          *
484          * $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't
485          * need that object to manipulate directly, but it is available if you need to
486          * abort the request manually.
487          *
488          * '''Note:''' If you specify the dataType option described below, make sure
489          * the server sends the correct MIME type in the response (eg. xml as "text/xml").
490          * Sending the wrong MIME type can lead to unexpected problems in your script.
491          * See [[Specifying the Data Type for AJAX Requests]] for more information.
492          *
493          * Supported datatypes are (see dataType option):
494          *
495          * "xml": Returns a XML document that can be processed via jQuery.
496          *
497          * "html": Returns HTML as plain text, included script tags are evaluated.
498          *
499          * "script": Evaluates the response as Javascript and returns it as plain text.
500          *
501          * "json": Evaluates the response as JSON and returns a Javascript Object
502          *
503          * $.ajax() takes one argument, an object of key/value pairs, that are
504          * used to initalize and handle the request. These are all the key/values that can
505          * be used:
506          *
507          * (String) url - The URL to request.
508          *
509          * (String) type - The type of request to make ("POST" or "GET"), default is "GET".
510          *
511          * (String) dataType - The type of data that you're expecting back from
512          * the server. No default: If the server sends xml, the responseXML, otherwise
513          * the responseText is passed to the success callback.
514          *
515          * (Boolean) ifModified - Allow the request to be successful only if the
516          * response has changed since the last request. This is done by checking the
517          * Last-Modified header. Default value is false, ignoring the header.
518          *
519          * (Number) timeout - Local timeout in milliseconds to override global timeout, eg. to give a
520          * single request a longer timeout while all others timeout after 1 second.
521          * See $.ajaxTimeout() for global timeouts.
522          *
523          * (Boolean) global - Whether to trigger global AJAX event handlers for
524          * this request, default is true. Set to false to prevent that global handlers
525          * like ajaxStart or ajaxStop are triggered.
526          *
527          * (Function) error - A function to be called if the request fails. The
528          * function gets passed tree arguments: The XMLHttpRequest object, a
529          * string describing the type of error that occurred and an optional
530          * exception object, if one occured.
531          *
532          * (Function) success - A function to be called if the request succeeds. The
533          * function gets passed one argument: The data returned from the server,
534          * formatted according to the 'dataType' parameter.
535          *
536          * (Function) complete - A function to be called when the request finishes. The
537          * function gets passed two arguments: The XMLHttpRequest object and a
538          * string describing the type of success of the request.
539          *
540          * (Object|String) data - Data to be sent to the server. Converted to a query
541          * string, if not already a string. Is appended to the url for GET-requests.
542          * See processData option to prevent this automatic processing.
543          *
544          * (String) contentType - When sending data to the server, use this content-type.
545          * Default is "application/x-www-form-urlencoded", which is fine for most cases.
546          *
547          * (Boolean) processData - By default, data passed in to the data option as an object
548          * other as string will be processed and transformed into a query string, fitting to
549          * the default content-type "application/x-www-form-urlencoded". If you want to send
550          * DOMDocuments, set this option to false.
551          *
552          * (Boolean) async - By default, all requests are sent asynchronous (set to true).
553          * If you need synchronous requests, set this option to false.
554          *
555          * (Function) beforeSend - A pre-callback to set custom headers etc., the
556          * XMLHttpRequest is passed as the only argument.
557          *
558          * @example $.ajax({
559          *   type: "GET",
560          *   url: "test.js",
561          *   dataType: "script"
562          * })
563          * @desc Load and execute a JavaScript file.
564          *
565          * @example $.ajax({
566          *   type: "POST",
567          *   url: "some.php",
568          *   data: "name=John&location=Boston",
569          *   success: function(msg){
570          *     alert( "Data Saved: " + msg );
571          *   }
572          * });
573          * @desc Save some data to the server and notify the user once its complete.
574          *
575          * @example var html = $.ajax({
576          *  url: "some.php",
577          *  async: false
578          * }).responseText;
579          * @desc Loads data synchronously. Blocks the browser while the requests is active.
580          * It is better to block user interaction by other means when synchronization is
581          * necessary.
582          *
583          * @example var xmlDocument = [create xml document];
584          * $.ajax({
585          *   url: "page.php",
586          *   processData: false,
587          *   data: xmlDocument,
588          *   success: handleResponse
589          * });
590          * @desc Sends an xml document as data to the server. By setting the processData
591          * option to false, the automatic conversion of data to strings is prevented.
592          * 
593          * @name $.ajax
594          * @type XMLHttpRequest
595          * @param Map properties Key/value pairs to initialize the request with.
596          * @cat Ajax
597          * @see ajaxSetup(Map)
598          */
599         ajax: function( s ) {
600                 // Extend the settings, but re-extend 's' so that it can be
601                 // checked again later (in the test suite, specifically)
602                 s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
603
604                 // if data available
605                 if ( s.data ) {
606                         // convert data if not already a string
607                         if ( s.processData && typeof s.data != "string" )
608                                 s.data = jQuery.param(s.data);
609
610                         // append data to url for get requests
611                         if ( s.type.toLowerCase() == "get" ) {
612                                 // "?" + data or "&" + data (in case there are already params)
613                                 s.url += (s.url.indexOf("?") > -1 ? "&" : "?") + s.data;
614
615                                 // IE likes to send both get and post data, prevent this
616                                 s.data = null;
617                         }
618                 }
619
620                 // Watch for a new set of requests
621                 if ( s.global && ! jQuery.active++ )
622                         jQuery.event.trigger( "ajaxStart" );
623
624                 var requestDone = false;
625
626                 // Create the request object; Microsoft failed to properly
627                 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
628                 var xml = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
629
630                 // Open the socket
631                 xml.open(s.type, s.url, s.async);
632
633                 // Set the correct header, if data is being sent
634                 if ( s.data )
635                         xml.setRequestHeader("Content-Type", s.contentType);
636
637                 // Set the If-Modified-Since header, if ifModified mode.
638                 if ( s.ifModified )
639                         xml.setRequestHeader("If-Modified-Since",
640                                 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
641
642                 // Set header so the called script knows that it's an XMLHttpRequest
643                 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
644
645                 // Allow custom headers/mimetypes
646                 if( s.beforeSend )
647                         s.beforeSend(xml);
648                         
649                 if ( s.global )
650                     jQuery.event.trigger("ajaxSend", [xml, s]);
651
652                 // Wait for a response to come back
653                 var onreadystatechange = function(isTimeout){
654                         // The transfer is complete and the data is available, or the request timed out
655                         if ( !requestDone && xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
656                                 requestDone = true;
657                                 
658                                 // clear poll interval
659                                 if (ival) {
660                                         clearInterval(ival);
661                                         ival = null;
662                                 }
663                                 
664                                 var status = isTimeout == "timeout" && "timeout" ||
665                                         !jQuery.httpSuccess( xml ) && "error" ||
666                                         s.ifModified && jQuery.httpNotModified( xml, s.url ) && "notmodified" ||
667                                         "success";
668
669                                 if ( status == "success" ) {
670                                         // Watch for, and catch, XML document parse errors
671                                         try {
672                                                 // process the data (runs the xml through httpData regardless of callback)
673                                                 var data = jQuery.httpData( xml, s.dataType );
674                                         } catch(e) {
675                                                 status = "parsererror";
676                                         }
677                                 }
678
679                                 // Make sure that the request was successful or notmodified
680                                 if ( status == "success" ) {
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 ( s.ifModified && modRes )
688                                                 jQuery.lastModified[s.url] = modRes;
689         
690                                         // If a local callback was specified, fire it and pass it the data
691                                         if ( s.success )
692                                                 s.success( data, status );
693         
694                                         // Fire the global callback
695                                         if ( s.global )
696                                                 jQuery.event.trigger( "ajaxSuccess", [xml, s] );
697                                 } else
698                                         jQuery.handleError(s, xml, status);
699
700                                 // The request was completed
701                                 if( s.global )
702                                         jQuery.event.trigger( "ajaxComplete", [xml, s] );
703
704                                 // Handle the global AJAX counter
705                                 if ( s.global && ! --jQuery.active )
706                                         jQuery.event.trigger( "ajaxStop" );
707
708                                 // Process result
709                                 if ( s.complete )
710                                         s.complete(xml, status);
711
712                                 // Stop memory leaks
713                                 if(s.async)
714                                         xml = null;
715                         }
716                 };
717                 
718                 if ( s.async ) {
719                         // don't attach the handler to the request, just poll it instead
720                         var ival = setInterval(onreadystatechange, 13); 
721
722                         // Timeout checker
723                         if ( s.timeout > 0 )
724                                 setTimeout(function(){
725                                         // Check to see if the request is still happening
726                                         if ( xml ) {
727                                                 // Cancel the request
728                                                 xml.abort();
729         
730                                                 if( !requestDone )
731                                                         onreadystatechange( "timeout" );
732                                         }
733                                 }, s.timeout);
734                 }
735                         
736                 // Send the data
737                 try {
738                         xml.send(s.data);
739                 } catch(e) {
740                         jQuery.handleError(s, xml, null, e);
741                 }
742                 
743                 // firefox 1.5 doesn't fire statechange for sync requests
744                 if ( !s.async )
745                         onreadystatechange();
746                 
747                 // return XMLHttpRequest to allow aborting the request etc.
748                 return xml;
749         },
750
751         handleError: function( s, xml, status, e ) {
752                 // If a local callback was specified, fire it
753                 if ( s.error ) s.error( xml, status, e );
754
755                 // Fire the global callback
756                 if ( s.global )
757                         jQuery.event.trigger( "ajaxError", [xml, s, e] );
758         },
759
760         // Counter for holding the number of active queries
761         active: 0,
762
763         // Determines if an XMLHttpRequest was successful or not
764         httpSuccess: function( r ) {
765                 try {
766                         return !r.status && location.protocol == "file:" ||
767                                 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
768                                 jQuery.browser.safari && r.status == undefined;
769                 } catch(e){}
770                 return false;
771         },
772
773         // Determines if an XMLHttpRequest returns NotModified
774         httpNotModified: function( xml, url ) {
775                 try {
776                         var xmlRes = xml.getResponseHeader("Last-Modified");
777
778                         // Firefox always returns 200. check Last-Modified date
779                         return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
780                                 jQuery.browser.safari && xml.status == undefined;
781                 } catch(e){}
782                 return false;
783         },
784
785         /* Get the data out of an XMLHttpRequest.
786          * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
787          * otherwise return plain text.
788          * (String) data - The type of data that you're expecting back,
789          * (e.g. "xml", "html", "script")
790          */
791         httpData: function( r, type ) {
792                 var ct = r.getResponseHeader("content-type");
793                 var xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0;
794                 data = xml ? r.responseXML : r.responseText;
795
796                 if ( xml && data.documentElement.tagName == "parsererror" )
797                         throw "parsererror";
798
799                 // If the type is "script", eval it in global context
800                 if ( type == "script" )
801                         jQuery.globalEval( data );
802
803                 // Get the JavaScript object, if JSON is used.
804                 if ( type == "json" )
805                         data = eval("(" + data + ")");
806
807                 return data;
808         },
809
810         // Serialize an array of form elements or a set of
811         // key/values into a query string
812         param: function( a ) {
813                 var s = [];
814
815                 // If an array was passed in, assume that it is an array
816                 // of form elements
817                 if ( a.constructor == Array || a.jquery )
818                         // Serialize the form elements
819                         jQuery.each( a, function(){
820                                 s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
821                         });
822
823                 // Otherwise, assume that it's an object of key/value pairs
824                 else
825                         // Serialize the key/values
826                         for ( var j in a )
827                                 // If the value is an array then the key names need to be repeated
828                                 if ( a[j] && a[j].constructor == Array )
829                                         jQuery.each( a[j], function(){
830                                                 s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
831                                         });
832                                 else
833                                         s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j] ) );
834
835                 // Return the resulting serialization
836                 return s.join("&");
837         }
838
839 });