Added a bunch of fixes for AJAX timeouts, etc. in Safari.
[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                 var requestDone = false;
149         
150                 // Create the request object
151                 var xml = new XMLHttpRequest();
152         
153                 // Open the socket
154                 xml.open(type || "GET", url, true);
155                 
156                 // Set the correct header, if data is being sent
157                 if ( data )
158                         xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
159                 
160                 // Set the If-Modified-Since header, if ifModified mode.
161                 if ( ifModified )
162                         xml.setRequestHeader("If-Modified-Since",
163                                 jQuery.lastModified[url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
164                 
165                 // Set header so calling script knows that it's an XMLHttpRequest
166                 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
167         
168                 // Make sure the browser sends the right content length
169                 if ( xml.overrideMimeType )
170                         xml.setRequestHeader("Connection", "close");
171                 
172                 // Wait for a response to come back
173                 var onreadystatechange = function(istimeout){
174                         // The transfer is complete and the data is available, or the request timed out
175                         if ( xml && (xml.readyState == 4 || istimeout == "timeout") ) {
176                                 requestDone = true;
177
178                                 var status = jQuery.httpSuccess( xml ) && istimeout != "timeout" ?
179                                         ifModified && jQuery.httpNotModified( xml, url ) ? "notmodified" : "success" : "error";
180                                 
181                                 // Make sure that the request was successful or notmodified
182                                 if ( status != "error" ) {
183                                         // Cache Last-Modified header, if ifModified mode.
184                                         var modRes = xml.getResponseHeader("Last-Modified");
185                                         if ( ifModified && modRes ) jQuery.lastModified[url] = modRes;
186                                         
187                                         // If a local callback was specified, fire it
188                                         if ( success ) success( xml, status );
189                                         
190                                         // Fire the global callback
191                                         jQuery.event.trigger( "ajaxSuccess" );
192                                 
193                                 // Otherwise, the request was not successful
194                                 } else {
195                                         // If a local callback was specified, fire it
196                                         if ( error ) error( xml, status );
197                                         
198                                         // Fire the global callback
199                                         jQuery.event.trigger( "ajaxError" );
200                                 }
201                                 
202                                 // The request was completed
203                                 jQuery.event.trigger( "ajaxComplete" );
204                                 
205                                 // Handle the global AJAX counter
206                                 if ( ! --jQuery.active )
207                                         jQuery.event.trigger( "ajaxStop" );
208         
209                                 // Process result
210                                 if ( ret ) ret(xml, status);
211                                 
212                                 // Stop memory leaks
213                                 xml.onreadystatechange = function(){};
214                                 xml = null;
215                                 
216                         }
217                 };
218                 xml.onreadystatechange = onreadystatechange;
219                 
220                 // Timeout checker
221                 if(jQuery.timeout > 0)
222                         setTimeout(function(){
223                                 // Check to see if the request is still happening
224                                 if (xml) {
225                                         // Cancel the request
226                                         xml.abort();
227
228                                         if ( !requestDone ) onreadystatechange( "timeout" );
229
230                                         // Clear from memory
231                                         xml = null;
232                                 }
233                         }, jQuery.timeout);
234                 
235                 // Send the data
236                 xml.send(data);
237         },
238         
239         // Counter for holding the number of active queries
240         active: 0,
241         
242         // Determines if an XMLHttpRequest was successful or not
243         httpSuccess: function(r) {
244                 try {
245                         return !r.status && location.protocol == "file:" ||
246                                 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
247                                 jQuery.browser.safari && r.status == undefined;
248                 } catch(e){}
249
250                 return false;
251         },
252
253         // Determines if an XMLHttpRequest returns NotModified
254         httpNotModified: function(xml, url) {
255                 try {
256                         var xmlRes = xml.getResponseHeader("Last-Modified");
257
258                         // Firefox always returns 200. check Last-Modified date
259                         return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
260                                 jQuery.browser.safari && xml.status == undefined;
261                 } catch(e){}
262
263                 return false;
264         },
265         
266         // Get the data out of an XMLHttpRequest.
267         // Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
268         // otherwise return plain text.
269         httpData: function(r,type) {
270                 var ct = r.getResponseHeader("content-type");
271                 var data = !type && ct && ct.indexOf("xml") >= 0;
272                 data = type == "xml" || data ? r.responseXML : r.responseText;
273
274                 // If the type is "script", eval it
275                 if ( type == "script" ) eval.call( window, data );
276
277                 return data;
278         },
279         
280         // Serialize an array of form elements or a set of
281         // key/values into a query string
282         param: function(a) {
283                 var s = [];
284                 
285                 // If an array was passed in, assume that it is an array
286                 // of form elements
287                 if ( a.constructor == Array ) {
288                         // Serialize the form elements
289                         for ( var i = 0; i < a.length; i++ )
290                                 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
291                         
292                 // Otherwise, assume that it's an object of key/value pairs
293                 } else {
294                         // Serialize the key/values
295                         for ( var j in a )
296                                 s.push( j + "=" + encodeURIComponent( a[j] ) );
297                 }
298                 
299                 // Return the resulting serialization
300                 return s.join("&");
301         }
302
303 });