Made some minor fixes to how content-type and context is handled on remote XML files.
[jquery.git] / src / ajax / ajax.js
1 // AJAX Plugin
2 // Docs Here:
3 // http://jquery.com/docs/ajax/
4
5 /**
6  * Load HTML from a remote file and inject it into the DOM
7  */
8 jQuery.fn.loadIfModified = function( url, params, callback ) {
9         this.load( url, params, callback, 1 );
10 };
11
12 jQuery.fn.load = function( url, params, callback, ifModified ) {
13         if ( url.constructor == Function )
14                 return this.bind("load", url);
15
16         callback = callback || function(){};
17
18         // Default to a GET request
19         var type = "GET";
20
21         // If the second parameter was provided
22         if ( params ) {
23                 // If it's a function
24                 if ( params.constructor == Function ) {
25                         // We assume that it's the callback
26                         callback = params;
27                         params = null;
28                         
29                 // Otherwise, build a param string
30                 } else {
31                         params = jQuery.param( params );
32                         type = "POST";
33                 }
34         }
35         
36         var self = this;
37         
38         // Request the remote document
39         jQuery.ajax( type, url, params,function(res, status){
40                 
41                 if ( status == "success" || !ifModified && status == "notmodified" ) {
42                         // Inject the HTML into all the matched elements
43                         self.html(res.responseText).each( callback, [res.responseText, status] );
44                         
45                         // Execute all the scripts inside of the newly-injected HTML
46                         $("script", self).each(function(){
47                                 if ( this.src )
48                                         $.getScript( this.src );
49                                 else
50                                         eval.call( window, this.text || this.textContent || this.innerHTML || "" );
51                         });
52                 } else
53                         callback.apply( self, [res.responseText, status] );
54
55         }, ifModified);
56         
57         return this;
58 };
59
60 // If IE is used, create a wrapper for the XMLHttpRequest object
61 if ( jQuery.browser.msie )
62         XMLHttpRequest = function(){
63                 return new ActiveXObject(
64                         navigator.userAgent.indexOf("MSIE 5") >= 0 ?
65                         "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
66                 );
67         };
68
69 // Attach a bunch of functions for handling common AJAX events
70 new function(){
71         var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(',');
72         
73         for ( var i = 0; i < e.length; i++ ) new function(){
74                 var o = e[i];
75                 jQuery.fn[o] = function(f){
76                         return this.bind(o, f);
77                 };
78         };
79 };
80
81 jQuery.extend({
82
83         /**
84          * Load a remote page using a GET request
85          */
86         get: function( url, data, callback, type, ifModified ) {
87                 if ( data.constructor == Function ) {
88                         type = callback;
89                         callback = data;
90                         data = null;
91                 }
92                 
93                 if ( data ) url += "?" + jQuery.param(data);
94                 
95                 // Build and start the HTTP Request
96                 jQuery.ajax( "GET", url, null, function(r, status) {
97                         if ( callback ) callback( jQuery.httpData(r,type), status );
98                 }, ifModified);
99         },
100
101         getIfModified: function( url, data, callback, type ) {
102                 jQuery.get(url, data, callback, type, 1);
103         },
104
105         getScript: function( url, data, callback ) {
106                 jQuery.get(url, data, callback, "script");
107         },
108         
109         /**
110          * Load a remote page using a POST request.
111          */
112         post: function( url, data, callback, type ) {
113                 // Build and start the HTTP Request
114                 jQuery.ajax( "POST", url, jQuery.param(data), function(r, status) {
115                         if ( callback ) callback( jQuery.httpData(r,type), status );
116                 });
117         },
118         
119         // timeout (ms)
120         timeout: 0,
121
122         ajaxTimeout: function(timeout) {
123                 jQuery.timeout = timeout;
124         },
125
126         // Last-Modified header cache for next request
127         lastModified: {},
128         
129         /**
130          * A common wrapper for making XMLHttpRequests
131          */
132         ajax: function( type, url, data, ret, ifModified ) {
133                 // If only a single argument was passed in,
134                 // assume that it is a object of key/value pairs
135                 if ( !url ) {
136                         ret = type.complete;
137                         var success = type.success;
138                         var error = type.error;
139                         data = type.data;
140                         url = type.url;
141                         type = type.type;
142                 }
143                 
144                 // Watch for a new set of requests
145                 if ( ! jQuery.active++ )
146                         jQuery.event.trigger( "ajaxStart" );
147         
148                 // Create the request object
149                 var xml = new XMLHttpRequest();
150         
151                 // Open the socket
152                 xml.open(type || "GET", url, true);
153                 
154                 // Set the correct header, if data is being sent
155                 if ( data )
156                         xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
157                 
158                 // Set the If-Modified-Since header, if ifModified mode.
159                 if ( ifModified )
160                         xml.setRequestHeader("If-Modified-Since",
161                                 jQuery.lastModified[url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
162                 
163                 // Set header so calling script knows that it's an XMLHttpRequest
164                 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
165         
166                 // Make sure the browser sends the right content length
167                 if ( xml.overrideMimeType )
168                         xml.setRequestHeader("Connection", "close");
169                 
170                 // Wait for a response to come back
171                 var onreadystatechange = function(istimeout){
172                         // The transfer is complete and the data is available, or the request timed out
173                         if ( xml && (xml.readyState == 4 || istimeout) ) {
174                                 var status = jQuery.httpSuccess( xml ) && !istimeout ?
175                                         ifModified && jQuery.httpNotModified( xml, url ) ? "notmodified" : "success" : "error";
176                                 
177                                 // Make sure that the request was successful or notmodified
178                                 if ( status != "error" ) {
179                                         // Cache Last-Modified header, if ifModified mode.
180                                         var modRes = xml.getResponseHeader("Last-Modified");
181                                         if ( ifModified && modRes ) jQuery.lastModified[url] = modRes;
182                                         
183                                         // If a local callback was specified, fire it
184                                         if ( success ) success( xml, status );
185                                         
186                                         // Fire the global callback
187                                         jQuery.event.trigger( "ajaxSuccess" );
188                                 
189                                 // Otherwise, the request was not successful
190                                 } else {
191                                         // If a local callback was specified, fire it
192                                         if ( error ) error( xml, status );
193                                         
194                                         // Fire the global callback
195                                         jQuery.event.trigger( "ajaxError" );
196                                 }
197                                 
198                                 // The request was completed
199                                 jQuery.event.trigger( "ajaxComplete" );
200                                 
201                                 // Handle the global AJAX counter
202                                 if ( ! --jQuery.active )
203                                         jQuery.event.trigger( "ajaxStop" );
204         
205                                 // Process result
206                                 if ( ret ) ret(xml, status);
207                                 
208                                 // Stop memory leaks
209                                 xml.onreadystatechange = function(){};
210                                 xml = null;
211                                 
212                         }
213                 };
214                 xml.onreadystatechange = onreadystatechange;
215                 
216                 // Timeout checker
217                 if(jQuery.timeout > 0)
218                         setTimeout(function(){
219                                 // Check to see if the request is still happening
220                                 if (xml) {
221                                         // Cancel the request
222                                         xml.abort();
223
224                                         // for Opera. Opera does't call onreadystatechange when aborted.
225                                         if (xml) onreadystatechange(1);
226
227                                         // Clear from memory
228                                         xml = null;
229                                 }
230                         }, jQuery.timeout);
231                 
232                 // Send the data
233                 xml.send(data);
234         },
235         
236         // Counter for holding the number of active queries
237         active: 0,
238         
239         // Determines if an XMLHttpRequest was successful or not
240         httpSuccess: function(r) {
241                 try {
242                         return r.status ?
243                                 ( r.status >= 200 && r.status < 300 ) || r.status == 304 :
244                                 location.protocol == "file:";
245                 } catch(e){}
246
247                 return false;
248         },
249
250         // Determines if an XMLHttpRequest returns NotModified
251         httpNotModified: function(xml, url) {
252                 try {
253                         var xmlRes = xml.getResponseHeader("Last-Modified");
254
255                         // Firefox always returns 200. check Last-Modified date
256                         if( xml.status == 304 || xmlRes == jQuery.lastModified[url]  ) return true;
257                 } catch(e){}
258
259                 return false;
260         },
261         
262         // Get the data out of an XMLHttpRequest.
263         // Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
264         // otherwise return plain text.
265         httpData: function(r,type) {
266                 var ct = r.getResponseHeader("content-type");
267                 var data = !type && ct && ct.indexOf("xml") >= 0;
268                 data = type == "xml" || data ? r.responseXML : r.responseText;
269
270                 // If the type is "script", eval it
271                 if ( type == "script" ) eval.call( window, data );
272
273                 return data;
274         },
275         
276         // Serialize an array of form elements or a set of
277         // key/values into a query string
278         param: function(a) {
279                 var s = [];
280                 
281                 // If an array was passed in, assume that it is an array
282                 // of form elements
283                 if ( a.constructor == Array ) {
284                         // Serialize the form elements
285                         for ( var i = 0; i < a.length; i++ )
286                                 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
287                         
288                 // Otherwise, assume that it's an object of key/value pairs
289                 } else {
290                         // Serialize the key/values
291                         for ( var j in a )
292                                 s.push( j + "=" + encodeURIComponent( a[j] ) );
293                 }
294                 
295                 // Return the resulting serialization
296                 return s.join("&");
297         }
298
299 });