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