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