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