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