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