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