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