Fix for bug #407, yet to be tested
[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          * @name load
37          * @type jQuery
38          * @param String url The URL of the HTML file to load.
39          * @param Object params A set of key/value pairs that will be sent as data to the server.
40          * @param Function callback A function to be executed whenever the data is loaded (parameters: responseText, status and reponse itself).
41          * @cat AJAX
42          */
43         load: function( url, params, callback, ifModified ) {
44                 if ( url.constructor == Function )
45                         return this.bind("load", url);
46
47                 callback = callback || function(){};
48
49                 // Default to a GET request
50                 var type = "GET";
51
52                 // If the second parameter was provided
53                 if ( params ) {
54                         // If it's a function
55                         if ( params.constructor == Function ) {
56                                 // We assume that it's the callback
57                                 callback = params;
58                                 params = null;
59
60                         // Otherwise, build a param string
61                         } else {
62                                 params = jQuery.param( params );
63                                 type = "POST";
64                         }
65                 }
66
67                 var self = this;
68
69                 // Request the remote document
70                 jQuery.ajax({
71                         url: url,
72                         type: type,
73                         data: params,
74                         ifModified: ifModified,
75                         complete: function(res, status){
76                                 if ( status == "success" || !ifModified && status == "notmodified" ) {
77                                         // Inject the HTML into all the matched elements
78                                         self.html(res.responseText)
79                                           // Execute all the scripts inside of the newly-injected HTML
80                                           .evalScripts()
81                                           // Execute callback
82                                           .each( callback, [res.responseText, status, res] );
83                                 } else
84                                         callback.apply( self, [res.responseText, status, res] );
85                         }
86                 });
87                 return this;
88         },
89
90         /**
91          * Serializes a set of input elements into a string of data.
92          * This will serialize all given elements. If you need
93          * serialization similar to the form submit of a browser,
94          * you should use the form plugin. This is also true for
95          * selects with multiple attribute set, only a single option
96          * is serialized.
97          *
98          * @example $("input[@type=text]").serialize();
99          * @before <input type='text' name='name' value='John'/>
100          * <input type='text' name='location' value='Boston'/>
101          * @after name=John&location=Boston
102          * @desc Serialize a selection of input elements to a string
103          *
104          * @name serialize
105          * @type String
106          * @cat AJAX
107          */
108         serialize: function() {
109                 return jQuery.param( this );
110         },
111
112         /**
113          * Evaluate all script tags inside this jQuery. If they have a src attribute,
114          * the script is loaded, otherwise it's content is evaluated.
115          *
116          * @name evalScripts
117          * @type jQuery
118          * @private
119          * @cat AJAX
120          */
121         evalScripts: function() {
122                 return this.find('script').each(function(){
123                         if ( this.src )
124                                 // for some weird reason, it doesn't work if the callback is ommited
125                                 jQuery.getScript( this.src );
126                         else
127                                 eval.call( window, this.text || this.textContent || this.innerHTML || "" );
128                 }).end();
129         }
130
131 });
132
133 // If IE is used, create a wrapper for the XMLHttpRequest object
134 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
135         XMLHttpRequest = function(){
136                 return new ActiveXObject(
137                         navigator.userAgent.indexOf("MSIE 5") >= 0 ?
138                         "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
139                 );
140         };
141
142 // Attach a bunch of functions for handling common AJAX events
143
144 /**
145  * Attach a function to be executed whenever an AJAX request begins.
146  *
147  * @example $("#loading").ajaxStart(function(){
148  *   $(this).show();
149  * });
150  * @desc Show a loading message whenever an AJAX request starts.
151  *
152  * @name ajaxStart
153  * @type jQuery
154  * @param Function callback The function to execute.
155  * @cat AJAX
156  */
157
158 /**
159  * Attach a function to be executed whenever all AJAX requests have ended.
160  *
161  * @example $("#loading").ajaxStop(function(){
162  *   $(this).hide();
163  * });
164  * @desc Hide a loading message after all the AJAX requests have stopped.
165  *
166  * @name ajaxStop
167  * @type jQuery
168  * @param Function callback The function to execute.
169  * @cat AJAX
170  */
171
172 /**
173  * Attach a function to be executed whenever an AJAX request completes.
174  *
175  * @example $("#msg").ajaxComplete(function(){
176  *   $(this).append("<li>Request Complete.</li>");
177  * });
178  * @desc Show a message when an AJAX request completes.
179  *
180  * @name ajaxComplete
181  * @type jQuery
182  * @param Function callback The function to execute.
183  * @cat AJAX
184  */
185
186 /**
187  * Attach a function to be executed whenever an AJAX request completes
188  * successfully.
189  *
190  * @example $("#msg").ajaxSuccess(function(){
191  *   $(this).append("<li>Successful Request!</li>");
192  * });
193  * @desc Show a message when an AJAX request completes successfully.
194  *
195  * @name ajaxSuccess
196  * @type jQuery
197  * @param Function callback The function to execute.
198  * @cat AJAX
199  */
200
201 /**
202  * Attach a function to be executed whenever an AJAX request fails.
203  *
204  * @example $("#msg").ajaxError(function(){
205  *   $(this).append("<li>Error requesting page.</li>");
206  * });
207  * @desc Show a message when an AJAX request fails.
208  *
209  * @name ajaxError
210  * @type jQuery
211  * @param Function callback The function to execute.
212  * @cat AJAX
213  */
214
215 new function(){
216         var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(",");
217
218         for ( var i = 0; i < e.length; i++ ) new function(){
219                 var o = e[i];
220                 jQuery.fn[o] = function(f){
221                         return this.bind(o, f);
222                 };
223         };
224 };
225
226 jQuery.extend({
227
228         /**
229          * Load a remote page using an HTTP GET request. All of the arguments to
230          * the method (except URL) are optional.
231          *
232          * @example $.get("test.cgi")
233          *
234          * @example $.get("test.cgi", { name: "John", time: "2pm" } )
235          *
236          * @example $.get("test.cgi", function(data){
237          *   alert("Data Loaded: " + data);
238          * })
239          *
240          * @example $.get("test.cgi",
241          *   { name: "John", time: "2pm" },
242          *   function(data){
243          *     alert("Data Loaded: " + data);
244          *   }
245          * )
246          *
247          * @name $.get
248          * @type undefined
249          * @param String url The URL of the page to load.
250          * @param Hash params A set of key/value pairs that will be sent to the server.
251          * @param Function callback A function to be executed whenever the data is loaded.
252          * @cat AJAX
253          */
254         get: function( url, data, callback, type, ifModified ) {
255                 // shift arguments if data argument was ommited
256                 if ( data && data.constructor == Function ) {
257                         callback = data;
258                         data = null;
259                 }
260
261                 // Delegate
262                 jQuery.ajax({
263                         url: url,
264                         data: data,
265                         success: callback,
266                         dataType: type,
267                         ifModified: ifModified
268                 });
269         },
270
271         /**
272          * Load a remote page using an HTTP GET request, only if it hasn't
273          * been modified since it was last retrieved. All of the arguments to
274          * the method (except URL) are optional.
275          *
276          * @example $.getIfModified("test.html")
277          *
278          * @example $.getIfModified("test.html", { name: "John", time: "2pm" } )
279          *
280          * @example $.getIfModified("test.cgi", function(data){
281          *   alert("Data Loaded: " + data);
282          * })
283          *
284          * @example $.getifModified("test.cgi",
285          *   { name: "John", time: "2pm" },
286          *   function(data){
287          *     alert("Data Loaded: " + data);
288          *   }
289          * )
290          *
291          * @name $.getIfModified
292          * @type undefined
293          * @param String url The URL of the page to load.
294          * @param Hash params A set of key/value pairs that will be sent to the server.
295          * @param Function callback A function to be executed whenever the data is loaded.
296          * @cat AJAX
297          */
298         getIfModified: function( url, data, callback, type ) {
299                 jQuery.get(url, data, callback, type, 1);
300         },
301
302         /**
303          * Loads, and executes, a remote JavaScript file using an HTTP GET request.
304          * All of the arguments to the method (except URL) are optional.
305          *
306          * @example $.getScript("test.js")
307          *
308          * @example $.getScript("test.js", function(){
309          *   alert("Script loaded and executed.");
310          * })
311          *
312          * @name $.getScript
313          * @type undefined
314          * @param String url The URL of the page to load.
315          * @param Function callback A function to be executed whenever the data is loaded.
316          * @cat AJAX
317          */
318         getScript: function( url, callback ) {
319                 if(callback)
320                         jQuery.get(url, null, callback, "script");
321                 else {
322                         jQuery.get(url, null, null, "script");
323                 }
324         },
325
326         /**
327          * Load a remote JSON object using an HTTP GET request.
328          * All of the arguments to the method (except URL) are optional.
329          *
330          * @example $.getJSON("test.js", function(json){
331          *   alert("JSON Data: " + json.users[3].name);
332          * })
333          *
334          * @example $.getJSON("test.js",
335          *   { name: "John", time: "2pm" },
336          *   function(json){
337          *     alert("JSON Data: " + json.users[3].name);
338          *   }
339          * )
340          *
341          * @name $.getJSON
342          * @type undefined
343          * @param String url The URL of the page to load.
344          * @param Hash params A set of key/value pairs that will be sent to the server.
345          * @param Function callback A function to be executed whenever the data is loaded.
346          * @cat AJAX
347          */
348         getJSON: function( url, data, callback ) {
349                 jQuery.get(url, data, callback, "json");
350         },
351
352         /**
353          * Load a remote page using an HTTP POST request. All of the arguments to
354          * the method (except URL) are optional.
355          *
356          * @example $.post("test.cgi")
357          *
358          * @example $.post("test.cgi", { name: "John", time: "2pm" } )
359          *
360          * @example $.post("test.cgi", function(data){
361          *   alert("Data Loaded: " + data);
362          * })
363          *
364          * @example $.post("test.cgi",
365          *   { name: "John", time: "2pm" },
366          *   function(data){
367          *     alert("Data Loaded: " + data);
368          *   }
369          * )
370          *
371          * @name $.post
372          * @type undefined
373          * @param String url The URL of the page to load.
374          * @param Hash params A set of key/value pairs that will be sent to the server.
375          * @param Function callback A function to be executed whenever the data is loaded.
376          * @cat AJAX
377          */
378         post: function( url, data, callback, type ) {
379                 // Delegate
380                 jQuery.ajax({
381                         type: "POST",
382                         url: url,
383                         data: data,
384                         success: callback,
385                         dataType: type
386                 });
387         },
388
389         // timeout (ms)
390         timeout: 0,
391
392         /**
393          * Set the timeout of all AJAX requests to a specific amount of time.
394          * This will make all future AJAX requests timeout after a specified amount
395          * of time (the default is no timeout).
396          *
397          * @example $.ajaxTimeout( 5000 );
398          * @desc Make all AJAX requests timeout after 5 seconds.
399          *
400          * @name $.ajaxTimeout
401          * @type undefined
402          * @param Number time How long before an AJAX request times out.
403          * @cat AJAX
404          */
405         ajaxTimeout: function(timeout) {
406                 jQuery.timeout = timeout;
407         },
408
409         // Last-Modified header cache for next request
410         lastModified: {},
411
412         /**
413          * Load a remote page using an HTTP request. This function is the primary
414          * means of making AJAX requests using jQuery. 
415          *
416          * $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't
417          * need that object to manipulate directly, but it is available if you need to
418          * abort the request manually.
419          *
420          * Please note: Make sure the server sends the right mimetype (eg. xml as
421          * "text/xml"). Sending the wrong mimetype will get you into serious
422          * trouble that jQuery can't solve.
423          *
424          * Supported datatypes (see dataType option) are:
425          *
426          * "xml": Returns a XML document that can be processed via jQuery.
427          *
428          * "html": Returns HTML as plain text, included script tags are evaluated.
429          *
430          * "script": Evaluates the response as Javascript and returns it as plain text.
431          *
432          * "json": Evaluates the response as JSON and returns a Javascript Object
433          *
434          * $.ajax() takes one property, an object of key/value pairs, that are
435          * used to initalize the request. These are all the key/values that can
436          * be passed in to 'prop':
437          *
438          * (String) url - The URL of the page to request.
439          *
440          * (String) type - The type of request to make (e.g. "POST" or "GET"), default is "GET".
441          *
442          * (String) dataType - The type of data that you're expecting back from
443          * the server. No default: If the server sends xml, the responseXML, otherwise
444          * the responseText is is passed to the success callback.
445          *
446          * (Boolean) ifModified - Allow the request to be successful only if the
447          * response has changed since the last request, default is false, ignoring
448          * the Last-Modified header
449          *
450          * (Number) timeout - Local timeout to override global timeout, eg. to give a
451          * single request a longer timeout while all others timeout after 1 seconds,
452          * see $.ajaxTimeout()
453          *
454          * (Boolean) global - Wheather to trigger global AJAX event handlers for
455          * this request, default is true. Set to false to prevent that global handlers
456          * like ajaxStart or ajaxStop are triggered.
457          *
458          * (Function) error - A function to be called if the request fails. The
459          * function gets passed two arguments: The XMLHttpRequest object and a
460          * string describing the type of error that occurred.
461          *
462          * (Function) success - A function to be called if the request succeeds. The
463          * function gets passed one argument: The data returned from the server,
464          * formatted according to the 'dataType' parameter.
465          *
466          * (Function) complete - A function to be called when the request finishes. The
467          * function gets passed two arguments: The XMLHttpRequest object and a
468          * string describing the type the success of the request.
469          *
470          * (String) data - Data to be sent to the server. Converted to a query
471          * string, if not already a string. Is appended to the url for GET-requests.
472          * Override processData option to prevent processing.
473          *
474          * (String) contentType - When sending data to the server, use this content-type,
475          * default is "application/x-www-form-urlencoded", which is fine for most cases.
476          *
477          * (Boolean) processData - By default, data passed in as an object other as string
478          * will be processed and transformed into a query string, fitting to the default
479          * content-type "application/x-www-form-urlencoded". If you want to send DOMDocuments,
480          * set this option to false.
481          *
482          * (Boolean) async - By default, all requests are send asynchronous (set to true).
483          * If you need synchronous requests, set this option to false.
484          *
485          * @example $.ajax({
486          *   type: "GET",
487          *   url: "test.js",
488          *   dataType: "script"
489          * })
490          * @desc Load and execute a JavaScript file.
491          *
492          * @example $.ajax({
493          *   type: "POST",
494          *   url: "some.php",
495          *   data: "name=John&location=Boston",
496          *   success: function(msg){
497          *     alert( "Data Saved: " + msg );
498          *   }
499          * });
500          * @desc Save some data to the server and notify the user once its complete.
501          *
502          * @name $.ajax
503          * @type XMLHttpRequest
504          * @param Hash prop A set of properties to initialize the request with.
505          * @cat AJAX
506          */
507         ajax: function( s ) {
508                 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
509                 s = jQuery.extend({
510                         global: true,
511                         ifModified: false,
512                         type: "GET",
513                         timeout: jQuery.timeout,
514                         complete: null,
515                         success: null,
516                         error: null,
517                         dataType: null,
518                         url: null,
519                         data: null,
520                         contentType: "application/x-www-form-urlencoded",
521                         processData: true,
522                         async: true
523                 }, s);
524
525                 // if data available
526                 if ( s.data ) {
527                         // convert data if not already a string
528                         if (s.processData && typeof s.data != 'string')
529                         s.data = jQuery.param(s.data);
530                         // append data to url for get requests
531                         if( s.type.toLowerCase() == "get" )
532                                 // "?" + data or "&" + data (in case there are already params)
533                                 s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data;
534                 }
535
536                 // Watch for a new set of requests
537                 if ( s.global && ! jQuery.active++ )
538                         jQuery.event.trigger( "ajaxStart" );
539
540                 var requestDone = false;
541
542                 // Create the request object
543                 var xml = new XMLHttpRequest();
544
545                 // Open the socket
546                 xml.open(s.type, s.url, s.async);
547
548                 // Set the correct header, if data is being sent
549                 if ( s.data )
550                         xml.setRequestHeader("Content-Type", s.contentType);
551
552                 // Set the If-Modified-Since header, if ifModified mode.
553                 if ( s.ifModified )
554                         xml.setRequestHeader("If-Modified-Since",
555                                 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
556
557                 // Set header so the called script knows that it's an XMLHttpRequest
558                 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
559
560                 // Make sure the browser sends the right content length
561                 if ( xml.overrideMimeType )
562                         xml.setRequestHeader("Connection", "close");
563
564                 // Wait for a response to come back
565                 var onreadystatechange = function(isTimeout){
566                         // The transfer is complete and the data is available, or the request timed out
567                         if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
568                                 requestDone = true;
569
570                                 var status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
571                                         s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
572
573                                 // Make sure that the request was successful or notmodified
574                                 if ( status != "error" ) {
575                                         // Cache Last-Modified header, if ifModified mode.
576                                         var modRes;
577                                         try {
578                                                 modRes = xml.getResponseHeader("Last-Modified");
579                                         } catch(e) {} // swallow exception thrown by FF if header is not available
580
581                                         if ( s.ifModified && modRes )
582                                                 jQuery.lastModified[s.url] = modRes;
583
584                                         // process the data (runs the xml through httpData regardless of callback)
585                                         var data = jQuery.httpData( xml, s.dataType );
586
587                                         // If a local callback was specified, fire it and pass it the data
588                                         if ( s.success )
589                                                 s.success( data, status );
590
591                                         // Fire the global callback
592                                         if( s.global )
593                                                 jQuery.event.trigger( "ajaxSuccess" );
594
595                                 // Otherwise, the request was not successful
596                                 } else {
597                                         // If a local callback was specified, fire it
598                                         if ( s.error ) s.error( xml, status );
599
600                                         // Fire the global callback
601                                         if( s.global )
602                                                 jQuery.event.trigger( "ajaxError" );
603                                 }
604
605                                 // The request was completed
606                                 if( s.global )
607                                         jQuery.event.trigger( "ajaxComplete" );
608
609                                 // Handle the global AJAX counter
610                                 if ( s.global && ! --jQuery.active )
611                                         jQuery.event.trigger( "ajaxStop" );
612
613                                 // Process result
614                                 if ( s.complete ) s.complete(xml, status);
615
616                                 // Stop memory leaks
617                                 xml.onreadystatechange = function(){};
618                                 xml = null;
619
620                         }
621                 };
622                 xml.onreadystatechange = onreadystatechange;
623
624                 // Timeout checker
625                 if(s.timeout > 0)
626                         setTimeout(function(){
627                                 // Check to see if the request is still happening
628                                 if (xml) {
629                                         // Cancel the request
630                                         xml.abort();
631
632                                         if ( !requestDone ) onreadystatechange( "timeout" );
633
634                                         // Clear from memory
635                                         xml = null;
636                                 }
637                         }, s.timeout);
638
639                 // Send the data
640                 xml.send(s.data);
641                 
642                 // return XMLHttpRequest to allow aborting the request etc.
643                 return xml;
644         },
645
646         // Counter for holding the number of active queries
647         active: 0,
648
649         // Determines if an XMLHttpRequest was successful or not
650         httpSuccess: function(r) {
651                 try {
652                         return !r.status && location.protocol == "file:" ||
653                                 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
654                                 jQuery.browser.safari && r.status == undefined;
655                 } catch(e){}
656
657                 return false;
658         },
659
660         // Determines if an XMLHttpRequest returns NotModified
661         httpNotModified: function(xml, url) {
662                 try {
663                         var xmlRes = xml.getResponseHeader("Last-Modified");
664
665                         // Firefox always returns 200. check Last-Modified date
666                         return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
667                                 jQuery.browser.safari && xml.status == undefined;
668                 } catch(e){}
669
670                 return false;
671         },
672
673         /* Get the data out of an XMLHttpRequest.
674          * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
675          * otherwise return plain text.
676          * (String) data - The type of data that you're expecting back,
677          * (e.g. "xml", "html", "script")
678          */
679         httpData: function(r,type) {
680                 var ct = r.getResponseHeader("content-type");
681                 var data = !type && ct && ct.indexOf("xml") >= 0;
682                 data = type == "xml" || data ? r.responseXML : r.responseText;
683
684                 // If the type is "script", eval it´in global context
685                 if ( type == "script" ) {
686                         if (window.execScript)
687                                 window.execScript( data );
688                         else
689                                 window.setTimeout( data, 0 );
690                 }
691
692                 // Get the JavaScript object, if JSON is used.
693                 if ( type == "json" ) eval( "data = " + data );
694
695                 // evaluate scripts within html
696                 if ( type == "html" ) jQuery("<div>").html(data).evalScripts();
697
698                 return data;
699         },
700
701         // Serialize an array of form elements or a set of
702         // key/values into a query string
703         param: function(a) {
704                 var s = [];
705
706                 // If an array was passed in, assume that it is an array
707                 // of form elements
708                 if ( a.constructor == Array || a.jquery ) {
709                         // Serialize the form elements
710                         for ( var i = 0; i < a.length; i++ )
711                                 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
712
713                 // Otherwise, assume that it's an object of key/value pairs
714                 } else {
715                         // Serialize the key/values
716                         for ( var j in a ) {
717                                 //if one value is array then treat each array value in part
718                                 if (typeof a[j] == 'object') {
719                                         for (var k = 0; k < a[j].length; k++) {
720                                                 s.push( j + "[]=" + encodeURIComponent( a[j][k] ) );
721                                         }
722                                 } else {
723                                         s.push( j + "=" + encodeURIComponent( a[j] ) );
724                                 }
725                         }
726                 }
727
728                 // Return the resulting serialization
729                 return s.join("&");
730         }
731
732 });