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