Fixes #8423. Never set X-Requested-With header automagically for cross-domain requests.
[jquery.git] / src / ajax / xhr.js
1 (function( jQuery ) {
2
3 var // #5280: next active xhr id and list of active xhrs' callbacks
4         xhrId = jQuery.now(),
5         xhrCallbacks,
6
7         // XHR used to determine supports properties
8         testXHR;
9
10 // #5280: Internet Explorer will keep connections alive if we don't abort on unload
11 function xhrOnUnloadAbort() {
12         jQuery( window ).unload(function() {
13                 // Abort all pending requests
14                 for ( var key in xhrCallbacks ) {
15                         xhrCallbacks[ key ]( 0, 1 );
16                 }
17         });
18 }
19
20 // Functions to create xhrs
21 function createStandardXHR() {
22         try {
23                 return new window.XMLHttpRequest();
24         } catch( e ) {}
25 }
26
27 function createActiveXHR() {
28         try {
29                 return new window.ActiveXObject( "Microsoft.XMLHTTP" );
30         } catch( e ) {}
31 }
32
33 // Create the request object
34 // (This is still attached to ajaxSettings for backward compatibility)
35 jQuery.ajaxSettings.xhr = window.ActiveXObject ?
36         /* Microsoft failed to properly
37          * implement the XMLHttpRequest in IE7 (can't request local files),
38          * so we use the ActiveXObject when it is available
39          * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
40          * we need a fallback.
41          */
42         function() {
43                 return !this.isLocal && createStandardXHR() || createActiveXHR();
44         } :
45         // For all other browsers, use the standard XMLHttpRequest object
46         createStandardXHR;
47
48 // Test if we can create an xhr object
49 testXHR = jQuery.ajaxSettings.xhr();
50 jQuery.support.ajax = !!testXHR;
51
52 // Does this browser support crossDomain XHR requests
53 jQuery.support.cors = testXHR && ( "withCredentials" in testXHR );
54
55 // No need for the temporary xhr anymore
56 testXHR = undefined;
57
58 // Create transport if the browser can provide an xhr
59 if ( jQuery.support.ajax ) {
60
61         jQuery.ajaxTransport(function( s ) {
62                 // Cross domain only allowed if supported through XMLHttpRequest
63                 if ( !s.crossDomain || jQuery.support.cors ) {
64
65                         var callback;
66
67                         return {
68                                 send: function( headers, complete ) {
69
70                                         // Get a new xhr
71                                         var xhr = s.xhr(),
72                                                 handle,
73                                                 i;
74
75                                         // Open the socket
76                                         // Passing null username, generates a login popup on Opera (#2865)
77                                         if ( s.username ) {
78                                                 xhr.open( s.type, s.url, s.async, s.username, s.password );
79                                         } else {
80                                                 xhr.open( s.type, s.url, s.async );
81                                         }
82
83                                         // Apply custom fields if provided
84                                         if ( s.xhrFields ) {
85                                                 for ( i in s.xhrFields ) {
86                                                         xhr[ i ] = s.xhrFields[ i ];
87                                                 }
88                                         }
89
90                                         // Override mime type if needed
91                                         if ( s.mimeType && xhr.overrideMimeType ) {
92                                                 xhr.overrideMimeType( s.mimeType );
93                                         }
94
95                                         // X-Requested-With header
96                                         // For cross-domain requests, seeing as conditions for a preflight are
97                                         // akin to a jigsaw puzzle, we simply never set it to be sure.
98                                         // (it can always be set on a per-request basis or even using ajaxSetup)
99                                         // For same-domain requests, won't change header if already provided.
100                                         if ( !s.crossDomain && !headers["X-Requested-With"] ) {
101                                                 headers[ "X-Requested-With" ] = "XMLHttpRequest";
102                                         }
103
104                                         // Need an extra try/catch for cross domain requests in Firefox 3
105                                         try {
106                                                 for ( i in headers ) {
107                                                         xhr.setRequestHeader( i, headers[ i ] );
108                                                 }
109                                         } catch( _ ) {}
110
111                                         // Do send the request
112                                         // This may raise an exception which is actually
113                                         // handled in jQuery.ajax (so no try/catch here)
114                                         xhr.send( ( s.hasContent && s.data ) || null );
115
116                                         // Listener
117                                         callback = function( _, isAbort ) {
118
119                                                 var status,
120                                                         statusText,
121                                                         responseHeaders,
122                                                         responses,
123                                                         xml;
124
125                                                 // Firefox throws exceptions when accessing properties
126                                                 // of an xhr when a network error occured
127                                                 // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
128                                                 try {
129
130                                                         // Was never called and is aborted or complete
131                                                         if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
132
133                                                                 // Only called once
134                                                                 callback = undefined;
135
136                                                                 // Do not keep as active anymore
137                                                                 if ( handle ) {
138                                                                         xhr.onreadystatechange = jQuery.noop;
139                                                                         delete xhrCallbacks[ handle ];
140                                                                 }
141
142                                                                 // If it's an abort
143                                                                 if ( isAbort ) {
144                                                                         // Abort it manually if needed
145                                                                         if ( xhr.readyState !== 4 ) {
146                                                                                 xhr.abort();
147                                                                         }
148                                                                 } else {
149                                                                         status = xhr.status;
150                                                                         responseHeaders = xhr.getAllResponseHeaders();
151                                                                         responses = {};
152                                                                         xml = xhr.responseXML;
153
154                                                                         // Construct response list
155                                                                         if ( xml && xml.documentElement /* #4958 */ ) {
156                                                                                 responses.xml = xml;
157                                                                         }
158                                                                         responses.text = xhr.responseText;
159
160                                                                         // Firefox throws an exception when accessing
161                                                                         // statusText for faulty cross-domain requests
162                                                                         try {
163                                                                                 statusText = xhr.statusText;
164                                                                         } catch( e ) {
165                                                                                 // We normalize with Webkit giving an empty statusText
166                                                                                 statusText = "";
167                                                                         }
168
169                                                                         // Filter status for non standard behaviors
170
171                                                                         // If the request is local and we have data: assume a success
172                                                                         // (success with no data won't get notified, that's the best we
173                                                                         // can do given current implementations)
174                                                                         if ( !status && s.isLocal && !s.crossDomain ) {
175                                                                                 status = responses.text ? 200 : 404;
176                                                                         // IE - #1450: sometimes returns 1223 when it should be 204
177                                                                         } else if ( status === 1223 ) {
178                                                                                 status = 204;
179                                                                         }
180                                                                 }
181                                                         }
182                                                 } catch( firefoxAccessException ) {
183                                                         if ( !isAbort ) {
184                                                                 complete( -1, firefoxAccessException );
185                                                         }
186                                                 }
187
188                                                 // Call complete if needed
189                                                 if ( responses ) {
190                                                         complete( status, statusText, responses, responseHeaders );
191                                                 }
192                                         };
193
194                                         // if we're in sync mode or it's in cache
195                                         // and has been retrieved directly (IE6 & IE7)
196                                         // we need to manually fire the callback
197                                         if ( !s.async || xhr.readyState === 4 ) {
198                                                 callback();
199                                         } else {
200                                                 // Create the active xhrs callbacks list if needed
201                                                 // and attach the unload handler
202                                                 if ( !xhrCallbacks ) {
203                                                         xhrCallbacks = {};
204                                                         xhrOnUnloadAbort();
205                                                 }
206                                                 // Add to list of active xhrs callbacks
207                                                 handle = xhrId++;
208                                                 xhr.onreadystatechange = xhrCallbacks[ handle ] = callback;
209                                         }
210                                 },
211
212                                 abort: function() {
213                                         if ( callback ) {
214                                                 callback(0,1);
215                                         }
216                                 }
217                         };
218                 }
219         });
220 }
221
222 })( jQuery );