Fix memory leaks in IE caused by the custom abort function of $.ajax. Fixes bug ...
[jquery.git] / src / ajax.js
1 (function( jQuery ) {
2
3 var jsc = jQuery.now(),
4         rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
5         rselectTextarea = /^(?:select|textarea)/i,
6         rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
7         rnoContent = /^(?:GET|HEAD)$/,
8         rbracket = /\[\]$/,
9         jsre = /\=\?(&|$)/,
10         rquery = /\?/,
11         rts = /([?&])_=[^&]*/,
12         rurl = /^(\w+:)?\/\/([^\/?#]+)/,
13         r20 = /%20/g,
14         rhash = /#.*$/,
15
16         // Keep a copy of the old load method
17         _load = jQuery.fn.load;
18
19 jQuery.fn.extend({
20         load: function( url, params, callback ) {
21                 if ( typeof url !== "string" && _load ) {
22                         return _load.apply( this, arguments );
23
24                 // Don't do a request if no elements are being requested
25                 } else if ( !this.length ) {
26                         return this;
27                 }
28
29                 var off = url.indexOf(" ");
30                 if ( off >= 0 ) {
31                         var selector = url.slice(off, url.length);
32                         url = url.slice(0, off);
33                 }
34
35                 // Default to a GET request
36                 var type = "GET";
37
38                 // If the second parameter was provided
39                 if ( params ) {
40                         // If it's a function
41                         if ( jQuery.isFunction( params ) ) {
42                                 // We assume that it's the callback
43                                 callback = params;
44                                 params = null;
45
46                         // Otherwise, build a param string
47                         } else if ( typeof params === "object" ) {
48                                 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
49                                 type = "POST";
50                         }
51                 }
52
53                 var self = this;
54
55                 // Request the remote document
56                 jQuery.ajax({
57                         url: url,
58                         type: type,
59                         dataType: "html",
60                         data: params,
61                         complete: function( res, status ) {
62                                 // If successful, inject the HTML into all the matched elements
63                                 if ( status === "success" || status === "notmodified" ) {
64                                         // See if a selector was specified
65                                         self.html( selector ?
66                                                 // Create a dummy div to hold the results
67                                                 jQuery("<div>")
68                                                         // inject the contents of the document in, removing the scripts
69                                                         // to avoid any 'Permission Denied' errors in IE
70                                                         .append(res.responseText.replace(rscript, ""))
71
72                                                         // Locate the specified elements
73                                                         .find(selector) :
74
75                                                 // If not, just inject the full result
76                                                 res.responseText );
77                                 }
78
79                                 if ( callback ) {
80                                         self.each( callback, [res.responseText, status, res] );
81                                 }
82                         }
83                 });
84
85                 return this;
86         },
87
88         serialize: function() {
89                 return jQuery.param(this.serializeArray());
90         },
91
92         serializeArray: function() {
93                 return this.map(function() {
94                         return this.elements ? jQuery.makeArray(this.elements) : this;
95                 })
96                 .filter(function() {
97                         return this.name && !this.disabled &&
98                                 (this.checked || rselectTextarea.test(this.nodeName) ||
99                                         rinput.test(this.type));
100                 })
101                 .map(function( i, elem ) {
102                         var val = jQuery(this).val();
103
104                         return val == null ?
105                                 null :
106                                 jQuery.isArray(val) ?
107                                         jQuery.map( val, function( val, i ) {
108                                                 return { name: elem.name, value: val };
109                                         }) :
110                                         { name: elem.name, value: val };
111                 }).get();
112         }
113 });
114
115 // Attach a bunch of functions for handling common AJAX events
116 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) {
117         jQuery.fn[o] = function( f ) {
118                 return this.bind(o, f);
119         };
120 });
121
122 jQuery.extend({
123         get: function( url, data, callback, type ) {
124                 // shift arguments if data argument was omited
125                 if ( jQuery.isFunction( data ) ) {
126                         type = type || callback;
127                         callback = data;
128                         data = null;
129                 }
130
131                 return jQuery.ajax({
132                         type: "GET",
133                         url: url,
134                         data: data,
135                         success: callback,
136                         dataType: type
137                 });
138         },
139
140         getScript: function( url, callback ) {
141                 return jQuery.get(url, null, callback, "script");
142         },
143
144         getJSON: function( url, data, callback ) {
145                 return jQuery.get(url, data, callback, "json");
146         },
147
148         post: function( url, data, callback, type ) {
149                 // shift arguments if data argument was omited
150                 if ( jQuery.isFunction( data ) ) {
151                         type = type || callback;
152                         callback = data;
153                         data = {};
154                 }
155
156                 return jQuery.ajax({
157                         type: "POST",
158                         url: url,
159                         data: data,
160                         success: callback,
161                         dataType: type
162                 });
163         },
164
165         ajaxSetup: function( settings ) {
166                 jQuery.extend( jQuery.ajaxSettings, settings );
167         },
168
169         ajaxSettings: {
170                 url: location.href,
171                 global: true,
172                 type: "GET",
173                 contentType: "application/x-www-form-urlencoded",
174                 processData: true,
175                 async: true,
176                 /*
177                 timeout: 0,
178                 data: null,
179                 username: null,
180                 password: null,
181                 traditional: false,
182                 */
183                 // This function can be overriden by calling jQuery.ajaxSetup
184                 xhr: function() {
185                         return new window.XMLHttpRequest();
186                 },
187                 accepts: {
188                         xml: "application/xml, text/xml",
189                         html: "text/html",
190                         script: "text/javascript, application/javascript",
191                         json: "application/json, text/javascript",
192                         text: "text/plain",
193                         _default: "*/*"
194                 }
195         },
196
197         ajax: function( origSettings ) {
198                 // IE8 leaks a lot when we've set abort, and IE6-8 a little
199                 // when we have set onreadystatechange. Bug #6242
200                 // XXX IE7 still leaks when abort is called, no matter what
201                 // we do
202                 function cleanup() {
203                         // IE6 will throw an error setting xhr.abort
204                         try {
205                                 xhr.abort = xhr.onreadystatechange = jQuery.noop;
206                         } catch(e) {}
207                 }
208
209                 var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
210                         jsonp, status, data, type = s.type.toUpperCase(), noContent = rnoContent.test(type);
211
212                 s.url = s.url.replace( rhash, "" );
213
214                 // Use original (not extended) context object if it was provided
215                 s.context = origSettings && origSettings.context != null ? origSettings.context : s;
216
217                 // convert data if not already a string
218                 if ( s.data && s.processData && typeof s.data !== "string" ) {
219                         s.data = jQuery.param( s.data, s.traditional );
220                 }
221
222                 // Handle JSONP Parameter Callbacks
223                 if ( s.dataType === "jsonp" ) {
224                         if ( type === "GET" ) {
225                                 if ( !jsre.test( s.url ) ) {
226                                         s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
227                                 }
228                         } else if ( !s.data || !jsre.test(s.data) ) {
229                                 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
230                         }
231                         s.dataType = "json";
232                 }
233
234                 // Build temporary JSONP function
235                 if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
236                         jsonp = s.jsonpCallback || ("jsonp" + jsc++);
237
238                         // Replace the =? sequence both in the query string and the data
239                         if ( s.data ) {
240                                 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
241                         }
242
243                         s.url = s.url.replace(jsre, "=" + jsonp + "$1");
244
245                         // We need to make sure
246                         // that a JSONP style response is executed properly
247                         s.dataType = "script";
248
249                         // Handle JSONP-style loading
250                         var customJsonp = window[ jsonp ];
251
252                         window[ jsonp ] = function( tmp ) {
253                                 if ( jQuery.isFunction( customJsonp ) ) {
254                                         customJsonp( tmp );
255
256                                 } else {
257                                         // Garbage collect
258                                         window[ jsonp ] = undefined;
259
260                                         try {
261                                                 delete window[ jsonp ];
262                                         } catch( jsonpError ) {}
263                                 }
264
265                                 data = tmp;
266                                 jQuery.handleSuccess( s, xhr, status, data );
267                                 jQuery.handleComplete( s, xhr, status, data );
268                                 
269                                 if ( head ) {
270                                         head.removeChild( script );
271                                 }
272                         };
273                 }
274
275                 if ( s.dataType === "script" && s.cache === null ) {
276                         s.cache = false;
277                 }
278
279                 if ( s.cache === false && noContent ) {
280                         var ts = jQuery.now();
281
282                         // try replacing _= if it is there
283                         var ret = s.url.replace(rts, "$1_=" + ts);
284
285                         // if nothing was replaced, add timestamp to the end
286                         s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
287                 }
288
289                 // If data is available, append data to url for GET/HEAD requests
290                 if ( s.data && noContent ) {
291                         s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
292                 }
293
294                 // Watch for a new set of requests
295                 if ( s.global && jQuery.active++ === 0 ) {
296                         jQuery.event.trigger( "ajaxStart" );
297                 }
298
299                 // Matches an absolute URL, and saves the domain
300                 var parts = rurl.exec( s.url ),
301                         remote = parts && (parts[1] && parts[1].toLowerCase() !== location.protocol || parts[2].toLowerCase() !== location.host);
302
303                 // If we're requesting a remote document
304                 // and trying to load JSON or Script with a GET
305                 if ( s.dataType === "script" && type === "GET" && remote ) {
306                         var head = document.getElementsByTagName("head")[0] || document.documentElement;
307                         var script = document.createElement("script");
308                         if ( s.scriptCharset ) {
309                                 script.charset = s.scriptCharset;
310                         }
311                         script.src = s.url;
312
313                         // Handle Script loading
314                         if ( !jsonp ) {
315                                 var done = false;
316
317                                 // Attach handlers for all browsers
318                                 script.onload = script.onreadystatechange = function() {
319                                         if ( !done && (!this.readyState ||
320                                                         this.readyState === "loaded" || this.readyState === "complete") ) {
321                                                 done = true;
322                                                 jQuery.handleSuccess( s, xhr, status, data );
323                                                 jQuery.handleComplete( s, xhr, status, data );
324
325                                                 // Handle memory leak in IE
326                                                 script.onload = script.onreadystatechange = null;
327                                                 if ( head && script.parentNode ) {
328                                                         head.removeChild( script );
329                                                 }
330                                         }
331                                 };
332                         }
333
334                         // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
335                         // This arises when a base node is used (#2709 and #4378).
336                         head.insertBefore( script, head.firstChild );
337
338                         // We handle everything using the script element injection
339                         return undefined;
340                 }
341
342                 var requestDone = false;
343
344                 // Create the request object
345                 var xhr = s.xhr();
346
347                 if ( !xhr ) {
348                         return;
349                 }
350
351                 // Open the socket
352                 // Passing null username, generates a login popup on Opera (#2865)
353                 if ( s.username ) {
354                         xhr.open(type, s.url, s.async, s.username, s.password);
355                 } else {
356                         xhr.open(type, s.url, s.async);
357                 }
358
359                 // Need an extra try/catch for cross domain requests in Firefox 3
360                 try {
361                         // Set content-type if data specified and content-body is valid for this type
362                         if ( (s.data != null && !noContent) || (origSettings && origSettings.contentType) ) {
363                                 xhr.setRequestHeader("Content-Type", s.contentType);
364                         }
365
366                         // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
367                         if ( s.ifModified ) {
368                                 if ( jQuery.lastModified[s.url] ) {
369                                         xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
370                                 }
371
372                                 if ( jQuery.etag[s.url] ) {
373                                         xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
374                                 }
375                         }
376
377                         // Set header so the called script knows that it's an XMLHttpRequest
378                         // Only send the header if it's not a remote XHR
379                         if ( !remote ) {
380                                 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
381                         }
382
383                         // Set the Accepts header for the server, depending on the dataType
384                         xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
385                                 s.accepts[ s.dataType ] + ", */*; q=0.01" :
386                                 s.accepts._default );
387                 } catch( headerError ) {}
388
389                 // Allow custom headers/mimetypes and early abort
390                 if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
391                         // Handle the global AJAX counter
392                         if ( s.global && jQuery.active-- === 1 ) {
393                                 jQuery.event.trigger( "ajaxStop" );
394                         }
395
396                         // close opended socket
397                         xhr.abort();
398                         return false;
399                 }
400
401                 if ( s.global ) {
402                         jQuery.triggerGlobal( s, "ajaxSend", [xhr, s] );
403                 }
404
405                 // Wait for a response to come back
406                 var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
407                         // The request was aborted
408                         if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
409                                 // Opera doesn't call onreadystatechange before this point
410                                 // so we simulate the call
411                                 if ( !requestDone ) {
412                                         jQuery.handleComplete( s, xhr, status, data );
413                                 }
414
415                                 requestDone = true;
416                                 if ( xhr ) {
417                                         cleanup();
418                                 }
419
420                         // The transfer is complete and the data is available, or the request timed out
421                         } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
422                                 requestDone = true;
423
424                                 status = isTimeout === "timeout" ?
425                                         "timeout" :
426                                         !jQuery.httpSuccess( xhr ) ?
427                                                 "error" :
428                                                 s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
429                                                         "notmodified" :
430                                                         "success";
431
432                                 var errMsg;
433
434                                 if ( status === "success" ) {
435                                         // Watch for, and catch, XML document parse errors
436                                         try {
437                                                 // process the data (runs the xml through httpData regardless of callback)
438                                                 data = jQuery.httpData( xhr, s.dataType, s );
439                                         } catch( parserError ) {
440                                                 status = "parsererror";
441                                                 errMsg = parserError;
442                                         }
443                                 }
444
445                                 // Make sure that the request was successful or notmodified
446                                 if ( status === "success" || status === "notmodified" ) {
447                                         // JSONP handles its own success callback
448                                         if ( !jsonp ) {
449                                                 jQuery.handleSuccess( s, xhr, status, data );
450                                         }
451                                 } else {
452                                         jQuery.handleError( s, xhr, status, errMsg );
453                                 }
454
455                                 // Fire the complete handlers
456                                 if ( !jsonp ) {
457                                         jQuery.handleComplete( s, xhr, status, data );
458                                 }
459
460                                 if ( isTimeout === "timeout" ) {
461                                         xhr.abort();
462                                 }
463
464                                 cleanup();
465                         }
466                 };
467
468                 // Override the abort handler, if we can (IE 6 doesn't allow it, but that's OK)
469                 // Opera doesn't fire onreadystatechange at all on abort
470                 try {
471                         var oldAbort = xhr.abort;
472                         xhr.abort = function() {
473                                 if ( xhr ) {
474                                         // oldAbort has no call property in IE7 so
475                                         // just do it this way, which works in all
476                                         // browsers
477                                         Function.prototype.call.call( oldAbort, xhr );
478                                 }
479
480                                 onreadystatechange( "abort" );
481                         };
482                 } catch( abortError ) {}
483
484                 // Timeout checker
485                 if ( s.async && s.timeout > 0 ) {
486                         setTimeout(function() {
487                                 // Check to see if the request is still happening
488                                 if ( xhr && !requestDone ) {
489                                         onreadystatechange( "timeout" );
490                                 }
491                         }, s.timeout);
492                 }
493
494                 // Send the data
495                 try {
496                         xhr.send( noContent || s.data == null ? null : s.data );
497
498                 } catch( sendError ) {
499                         jQuery.handleError( s, xhr, null, sendError );
500
501                         // Fire the complete handlers
502                         jQuery.handleComplete( s, xhr, status, data );
503                 }
504
505                 // firefox 1.5 doesn't fire statechange for sync requests
506                 if ( !s.async ) {
507                         onreadystatechange();
508                 }
509
510                 // return XMLHttpRequest to allow aborting the request etc.
511                 return xhr;
512         },
513
514         // Serialize an array of form elements or a set of
515         // key/values into a query string
516         param: function( a, traditional ) {
517                 var s = [],
518                         add = function( key, value ) {
519                                 // If value is a function, invoke it and return its value
520                                 value = jQuery.isFunction(value) ? value() : value;
521                                 s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
522                         };
523                 
524                 // Set traditional to true for jQuery <= 1.3.2 behavior.
525                 if ( traditional === undefined ) {
526                         traditional = jQuery.ajaxSettings.traditional;
527                 }
528                 
529                 // If an array was passed in, assume that it is an array of form elements.
530                 if ( jQuery.isArray(a) || a.jquery ) {
531                         // Serialize the form elements
532                         jQuery.each( a, function() {
533                                 add( this.name, this.value );
534                         });
535                         
536                 } else {
537                         // If traditional, encode the "old" way (the way 1.3.2 or older
538                         // did it), otherwise encode params recursively.
539                         for ( var prefix in a ) {
540                                 buildParams( prefix, a[prefix], traditional, add );
541                         }
542                 }
543
544                 // Return the resulting serialization
545                 return s.join("&").replace(r20, "+");
546         }
547 });
548
549 function buildParams( prefix, obj, traditional, add ) {
550         if ( jQuery.isArray(obj) && obj.length ) {
551                 // Serialize array item.
552                 jQuery.each( obj, function( i, v ) {
553                         if ( traditional || rbracket.test( prefix ) ) {
554                                 // Treat each array item as a scalar.
555                                 add( prefix, v );
556
557                         } else {
558                                 // If array item is non-scalar (array or object), encode its
559                                 // numeric index to resolve deserialization ambiguity issues.
560                                 // Note that rack (as of 1.0.0) can't currently deserialize
561                                 // nested arrays properly, and attempting to do so may cause
562                                 // a server error. Possible fixes are to modify rack's
563                                 // deserialization algorithm or to provide an option or flag
564                                 // to force array serialization to be shallow.
565                                 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
566                         }
567                 });
568                         
569         } else if ( !traditional && obj != null && typeof obj === "object" ) {
570                 if ( jQuery.isEmptyObject( obj ) ) {
571                         add( prefix, "" );
572
573                 // Serialize object item.
574                 } else {
575                         jQuery.each( obj, function( k, v ) {
576                                 buildParams( prefix + "[" + k + "]", v, traditional, add );
577                         });
578                 }
579                                         
580         } else {
581                 // Serialize scalar item.
582                 add( prefix, obj );
583         }
584 }
585
586 // This is still on the jQuery object... for now
587 // Want to move this to jQuery.ajax some day
588 jQuery.extend({
589
590         // Counter for holding the number of active queries
591         active: 0,
592
593         // Last-Modified header cache for next request
594         lastModified: {},
595         etag: {},
596
597         handleError: function( s, xhr, status, e ) {
598                 // If a local callback was specified, fire it
599                 if ( s.error ) {
600                         s.error.call( s.context, xhr, status, e );
601                 }
602
603                 // Fire the global callback
604                 if ( s.global ) {
605                         jQuery.triggerGlobal( s, "ajaxError", [xhr, s, e] );
606                 }
607         },
608
609         handleSuccess: function( s, xhr, status, data ) {
610                 // If a local callback was specified, fire it and pass it the data
611                 if ( s.success ) {
612                         s.success.call( s.context, data, status, xhr );
613                 }
614
615                 // Fire the global callback
616                 if ( s.global ) {
617                         jQuery.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
618                 }
619         },
620
621         handleComplete: function( s, xhr, status ) {
622                 // Process result
623                 if ( s.complete ) {
624                         s.complete.call( s.context, xhr, status );
625                 }
626
627                 // The request was completed
628                 if ( s.global ) {
629                         jQuery.triggerGlobal( s, "ajaxComplete", [xhr, s] );
630                 }
631
632                 // Handle the global AJAX counter
633                 if ( s.global && jQuery.active-- === 1 ) {
634                         jQuery.event.trigger( "ajaxStop" );
635                 }
636         },
637                 
638         triggerGlobal: function( s, type, args ) {
639                 (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
640         },
641
642         // Determines if an XMLHttpRequest was successful or not
643         httpSuccess: function( xhr ) {
644                 try {
645                         // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
646                         return !xhr.status && location.protocol === "file:" ||
647                                 xhr.status >= 200 && xhr.status < 300 ||
648                                 xhr.status === 304 || xhr.status === 1223;
649                 } catch(e) {}
650
651                 return false;
652         },
653
654         // Determines if an XMLHttpRequest returns NotModified
655         httpNotModified: function( xhr, url ) {
656                 var lastModified = xhr.getResponseHeader("Last-Modified"),
657                         etag = xhr.getResponseHeader("Etag");
658
659                 if ( lastModified ) {
660                         jQuery.lastModified[url] = lastModified;
661                 }
662
663                 if ( etag ) {
664                         jQuery.etag[url] = etag;
665                 }
666
667                 return xhr.status === 304;
668         },
669
670         httpData: function( xhr, type, s ) {
671                 var ct = xhr.getResponseHeader("content-type") || "",
672                         xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
673                         data = xml ? xhr.responseXML : xhr.responseText;
674
675                 if ( xml && data.documentElement.nodeName === "parsererror" ) {
676                         jQuery.error( "parsererror" );
677                 }
678
679                 // Allow a pre-filtering function to sanitize the response
680                 // s is checked to keep backwards compatibility
681                 if ( s && s.dataFilter ) {
682                         data = s.dataFilter( data, type );
683                 }
684
685                 // The filter can actually parse the response
686                 if ( typeof data === "string" ) {
687                         // Get the JavaScript object, if JSON is used.
688                         if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
689                                 data = jQuery.parseJSON( data );
690
691                         // If the type is "script", eval it in global context
692                         } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
693                                 jQuery.globalEval( data );
694                         }
695                 }
696
697                 return data;
698         }
699
700 });
701
702 /*
703  * Create the request object; Microsoft failed to properly
704  * implement the XMLHttpRequest in IE7 (can't request local files),
705  * so we use the ActiveXObject when it is available
706  * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
707  * we need a fallback.
708  */
709 if ( window.ActiveXObject ) {
710         jQuery.ajaxSettings.xhr = function() {
711                 if ( window.location.protocol !== "file:" ) {
712                         try {
713                                 return new window.XMLHttpRequest();
714                         } catch(xhrError) {}
715                 }
716
717                 try {
718                         return new window.ActiveXObject("Microsoft.XMLHTTP");
719                 } catch(activeError) {}
720         };
721 }
722
723 // Does this browser support XHR requests?
724 jQuery.support.ajax = !!jQuery.ajaxSettings.xhr();
725
726 })( jQuery );