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