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