jquery ajax: absolute urls were assumed to be cross domain. Closes #2816.
[jquery.git] / src / ajax.js
1 jQuery.fn.extend({
2         // Keep a copy of the old load
3         _load: jQuery.fn.load,
4
5         load: function( url, params, callback ) {
6                 if ( typeof url != 'string' )
7                         return this._load( url );
8
9                 var off = url.indexOf(" ");
10                 if ( off >= 0 ) {
11                         var selector = url.slice(off, url.length);
12                         url = url.slice(0, off);
13                 }
14
15                 callback = callback || function(){};
16
17                 // Default to a GET request
18                 var type = "GET";
19
20                 // If the second parameter was provided
21                 if ( params )
22                         // If it's a function
23                         if ( jQuery.isFunction( params ) ) {
24                                 // We assume that it's the callback
25                                 callback = params;
26                                 params = null;
27
28                         // Otherwise, build a param string
29                         } else {
30                                 params = jQuery.param( params );
31                                 type = "POST";
32                         }
33
34                 var self = this;
35
36                 // Request the remote document
37                 jQuery.ajax({
38                         url: url,
39                         type: type,
40                         dataType: "html",
41                         data: params,
42                         complete: function(res, status){
43                                 // If successful, inject the HTML into all the matched elements
44                                 if ( status == "success" || status == "notmodified" )
45                                         // See if a selector was specified
46                                         self.html( selector ?
47                                                 // Create a dummy div to hold the results
48                                                 jQuery("<div/>")
49                                                         // inject the contents of the document in, removing the scripts
50                                                         // to avoid any 'Permission Denied' errors in IE
51                                                         .append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
52
53                                                         // Locate the specified elements
54                                                         .find(selector) :
55
56                                                 // If not, just inject the full result
57                                                 res.responseText );
58
59                                 self.each( callback, [res.responseText, status, res] );
60                         }
61                 });
62                 return this;
63         },
64
65         serialize: function() {
66                 return jQuery.param(this.serializeArray());
67         },
68         serializeArray: function() {
69                 return this.map(function(){
70                         return jQuery.nodeName(this, "form") ?
71                                 jQuery.makeArray(this.elements) : this;
72                 })
73                 .filter(function(){
74                         return this.name && !this.disabled &&
75                                 (this.checked || /select|textarea/i.test(this.nodeName) ||
76                                         /text|hidden|password/i.test(this.type));
77                 })
78                 .map(function(i, elem){
79                         var val = jQuery(this).val();
80                         return val == null ? null :
81                                 val.constructor == Array ?
82                                         jQuery.map( val, function(val, i){
83                                                 return {name: elem.name, value: val};
84                                         }) :
85                                         {name: elem.name, value: val};
86                 }).get();
87         }
88 });
89
90 // Attach a bunch of functions for handling common AJAX events
91 jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
92         jQuery.fn[o] = function(f){
93                 return this.bind(o, f);
94         };
95 });
96
97 var jsc = now();
98
99 jQuery.extend({
100         get: function( url, data, callback, type ) {
101                 // shift arguments if data argument was ommited
102                 if ( jQuery.isFunction( data ) ) {
103                         callback = data;
104                         data = null;
105                 }
106
107                 return jQuery.ajax({
108                         type: "GET",
109                         url: url,
110                         data: data,
111                         success: callback,
112                         dataType: type
113                 });
114         },
115
116         getScript: function( url, callback ) {
117                 return jQuery.get(url, null, callback, "script");
118         },
119
120         getJSON: function( url, data, callback ) {
121                 return jQuery.get(url, data, callback, "json");
122         },
123
124         post: function( url, data, callback, type ) {
125                 if ( jQuery.isFunction( data ) ) {
126                         callback = data;
127                         data = {};
128                 }
129
130                 return jQuery.ajax({
131                         type: "POST",
132                         url: url,
133                         data: data,
134                         success: callback,
135                         dataType: type
136                 });
137         },
138
139         ajaxSetup: function( settings ) {
140                 jQuery.extend( jQuery.ajaxSettings, settings );
141         },
142
143         ajaxSettings: {
144                 global: true,
145                 type: "GET",
146                 timeout: 0,
147                 contentType: "application/x-www-form-urlencoded",
148                 processData: true,
149                 async: true,
150                 data: null,
151                 username: null,
152                 password: null,
153                 accepts: {
154                         xml: "application/xml, text/xml",
155                         html: "text/html",
156                         script: "text/javascript, application/javascript",
157                         json: "application/json, text/javascript",
158                         text: "text/plain",
159                         _default: "*/*"
160                 }
161         },
162
163         // Last-Modified header cache for next request
164         lastModified: {},
165
166         ajax: function( s ) {
167                 var jsonp, jsre = /=\?(&|$)/g, status, data;
168
169                 // Extend the settings, but re-extend 's' so that it can be
170                 // checked again later (in the test suite, specifically)
171                 s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
172
173                 // convert data if not already a string
174                 if ( s.data && s.processData && typeof s.data != "string" )
175                         s.data = jQuery.param(s.data);
176
177                 // Handle JSONP Parameter Callbacks
178                 if ( s.dataType == "jsonp" ) {
179                         if ( s.type.toLowerCase() == "get" ) {
180                                 if ( !s.url.match(jsre) )
181                                         s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
182                         } else if ( !s.data || !s.data.match(jsre) )
183                                 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
184                         s.dataType = "json";
185                 }
186
187                 // Build temporary JSONP function
188                 if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
189                         jsonp = "jsonp" + jsc++;
190
191                         // Replace the =? sequence both in the query string and the data
192                         if ( s.data )
193                                 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
194                         s.url = s.url.replace(jsre, "=" + jsonp + "$1");
195
196                         // We need to make sure
197                         // that a JSONP style response is executed properly
198                         s.dataType = "script";
199
200                         // Handle JSONP-style loading
201                         window[ jsonp ] = function(tmp){
202                                 data = tmp;
203                                 success();
204                                 complete();
205                                 // Garbage collect
206                                 window[ jsonp ] = undefined;
207                                 try{ delete window[ jsonp ]; } catch(e){}
208                                 if ( head )
209                                         head.removeChild( script );
210                         };
211                 }
212
213                 if ( s.dataType == "script" && s.cache == null )
214                         s.cache = false;
215
216                 if ( s.cache === false && s.type.toLowerCase() == "get" ) {
217                         var ts = now();
218                         // try replacing _= if it is there
219                         var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
220                         // if nothing was replaced, add timestamp to the end
221                         s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
222                 }
223
224                 // If data is available, append data to url for get requests
225                 if ( s.data && s.type.toLowerCase() == "get" ) {
226                         s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;
227
228                         // IE likes to send both get and post data, prevent this
229                         s.data = null;
230                 }
231
232                 // Watch for a new set of requests
233                 if ( s.global && ! jQuery.active++ )
234                         jQuery.event.trigger( "ajaxStart" );
235
236                 // If we're requesting a remote document
237                 // and trying to load JSON or Script with a GET
238                 if ( s.dataType == "script" && s.type.toLowerCase() == "get"
239                                 && jQuery.ajax.re.test(s.url) && jQuery.ajax.re.exec(s.url)[1] != location.host ){
240                         var head = document.getElementsByTagName("head")[0];
241                         var script = document.createElement("script");
242                         script.src = s.url;
243                         if (s.scriptCharset)
244                                 script.charset = s.scriptCharset;
245
246                         // Handle Script loading
247                         if ( !jsonp ) {
248                                 var done = false;
249
250                                 // Attach handlers for all browsers
251                                 script.onload = script.onreadystatechange = function(){
252                                         if ( !done && (!this.readyState ||
253                                                         this.readyState == "loaded" || this.readyState == "complete") ) {
254                                                 done = true;
255                                                 success();
256                                                 complete();
257                                                 head.removeChild( script );
258                                         }
259                                 };
260                         }
261
262                         head.appendChild(script);
263
264                         // We handle everything using the script element injection
265                         return undefined;
266                 }
267
268                 var requestDone = false;
269
270                 // Create the request object; Microsoft failed to properly
271                 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
272                 var xml = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
273
274                 // Open the socket
275                 xml.open(s.type, s.url, s.async, s.username, s.password);
276
277                 // Need an extra try/catch for cross domain requests in Firefox 3
278                 try {
279                         // Set the correct header, if data is being sent
280                         if ( s.data )
281                                 xml.setRequestHeader("Content-Type", s.contentType);
282
283                         // Set the If-Modified-Since header, if ifModified mode.
284                         if ( s.ifModified )
285                                 xml.setRequestHeader("If-Modified-Since",
286                                         jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
287
288                         // Set header so the called script knows that it's an XMLHttpRequest
289                         xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
290
291                         // Set the Accepts header for the server, depending on the dataType
292                         xml.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
293                                 s.accepts[ s.dataType ] + ", */*" :
294                                 s.accepts._default );
295                 } catch(e){}
296
297                 // Allow custom headers/mimetypes
298                 if ( s.beforeSend && s.beforeSend(xml, s) === false ) {
299                         // cleanup active request counter
300                         s.global && jQuery.active--;
301                         // close opended socket
302                         xml.abort();
303                         return false;
304                 }
305
306                 if ( s.global )
307                         jQuery.event.trigger("ajaxSend", [xml, s]);
308
309                 // Wait for a response to come back
310                 var onreadystatechange = function(isTimeout){
311                         // The transfer is complete and the data is available, or the request timed out
312                         if ( !requestDone && xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
313                                 requestDone = true;
314
315                                 // clear poll interval
316                                 if (ival) {
317                                         clearInterval(ival);
318                                         ival = null;
319                                 }
320
321                                 status = isTimeout == "timeout" && "timeout" ||
322                                         !jQuery.httpSuccess( xml ) && "error" ||
323                                         s.ifModified && jQuery.httpNotModified( xml, s.url ) && "notmodified" ||
324                                         "success";
325
326                                 if ( status == "success" ) {
327                                         // Watch for, and catch, XML document parse errors
328                                         try {
329                                                 // process the data (runs the xml through httpData regardless of callback)
330                                                 data = jQuery.httpData( xml, s.dataType );
331                                         } catch(e) {
332                                                 status = "parsererror";
333                                         }
334                                 }
335
336                                 // Make sure that the request was successful or notmodified
337                                 if ( status == "success" ) {
338                                         // Cache Last-Modified header, if ifModified mode.
339                                         var modRes;
340                                         try {
341                                                 modRes = xml.getResponseHeader("Last-Modified");
342                                         } catch(e) {} // swallow exception thrown by FF if header is not available
343
344                                         if ( s.ifModified && modRes )
345                                                 jQuery.lastModified[s.url] = modRes;
346
347                                         // JSONP handles its own success callback
348                                         if ( !jsonp )
349                                                 success();
350                                 } else
351                                         jQuery.handleError(s, xml, status);
352
353                                 // Fire the complete handlers
354                                 complete();
355
356                                 // Stop memory leaks
357                                 if ( s.async )
358                                         xml = null;
359                         }
360                 };
361
362                 if ( s.async ) {
363                         // don't attach the handler to the request, just poll it instead
364                         var ival = setInterval(onreadystatechange, 13);
365
366                         // Timeout checker
367                         if ( s.timeout > 0 )
368                                 setTimeout(function(){
369                                         // Check to see if the request is still happening
370                                         if ( xml ) {
371                                                 // Cancel the request
372                                                 xml.abort();
373
374                                                 if( !requestDone )
375                                                         onreadystatechange( "timeout" );
376                                         }
377                                 }, s.timeout);
378                 }
379
380                 // Send the data
381                 try {
382                         xml.send(s.data);
383                 } catch(e) {
384                         jQuery.handleError(s, xml, null, e);
385                 }
386
387                 // firefox 1.5 doesn't fire statechange for sync requests
388                 if ( !s.async )
389                         onreadystatechange();
390
391                 function success(){
392                         // If a local callback was specified, fire it and pass it the data
393                         if ( s.success )
394                                 s.success( data, status );
395
396                         // Fire the global callback
397                         if ( s.global )
398                                 jQuery.event.trigger( "ajaxSuccess", [xml, s] );
399                 }
400
401                 function complete(){
402                         // Process result
403                         if ( s.complete )
404                                 s.complete(xml, status);
405
406                         // The request was completed
407                         if ( s.global )
408                                 jQuery.event.trigger( "ajaxComplete", [xml, s] );
409
410                         // Handle the global AJAX counter
411                         if ( s.global && ! --jQuery.active )
412                                 jQuery.event.trigger( "ajaxStop" );
413                 }
414
415                 // return XMLHttpRequest to allow aborting the request etc.
416                 return xml;
417         },
418
419         handleError: function( s, xml, status, e ) {
420                 // If a local callback was specified, fire it
421                 if ( s.error ) s.error( xml, status, e );
422
423                 // Fire the global callback
424                 if ( s.global )
425                         jQuery.event.trigger( "ajaxError", [xml, s, e] );
426         },
427
428         // Counter for holding the number of active queries
429         active: 0,
430
431         // Determines if an XMLHttpRequest was successful or not
432         httpSuccess: function( r ) {
433                 try {
434                         // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
435                         return !r.status && location.protocol == "file:" ||
436                                 ( r.status >= 200 && r.status < 300 ) || r.status == 304 || r.status == 1223 ||
437                                 jQuery.browser.safari && r.status == undefined;
438                 } catch(e){}
439                 return false;
440         },
441
442         // Determines if an XMLHttpRequest returns NotModified
443         httpNotModified: function( xml, url ) {
444                 try {
445                         var xmlRes = xml.getResponseHeader("Last-Modified");
446
447                         // Firefox always returns 200. check Last-Modified date
448                         return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
449                                 jQuery.browser.safari && xml.status == undefined;
450                 } catch(e){}
451                 return false;
452         },
453
454         httpData: function( r, type ) {
455                 var ct = r.getResponseHeader("content-type"),
456                         xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
457                         data = xml ? r.responseXML : r.responseText;
458
459                 if ( xml && data.documentElement.tagName == "parsererror" )
460                         throw "parsererror";
461
462                 // If the type is "script", eval it in global context
463                 if ( type == "script" )
464                         jQuery.globalEval( data );
465
466                 // Get the JavaScript object, if JSON is used.
467                 if ( type == "json" )
468                         data = eval("(" + data + ")");
469
470                 return data;
471         },
472
473         // Serialize an array of form elements or a set of
474         // key/values into a query string
475         param: function( a ) {
476                 var s = [];
477
478                 // If an array was passed in, assume that it is an array
479                 // of form elements
480                 if ( a.constructor == Array || a.jquery )
481                         // Serialize the form elements
482                         jQuery.each( a, function(){
483                                 s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
484                         });
485
486                 // Otherwise, assume that it's an object of key/value pairs
487                 else
488                         // Serialize the key/values
489                         for ( var j in a )
490                                 // If the value is an array then the key names need to be repeated
491                                 if ( a[j] && a[j].constructor == Array )
492                                         jQuery.each( a[j], function(){
493                                                 s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
494                                         });
495                                 else
496                                         s.push( encodeURIComponent(j) + "=" + encodeURIComponent( jQuery.isFunction(a[j]) ? a[j]() : a[j] ) );
497
498                 // Return the resulting serialization
499                 return s.join("&").replace(/%20/g, "+");
500         }
501
502 });
503
504 // Matches an absolute URL, and saves the domain
505 jQuery.ajax.re = /^(?:\w+:)?\/\/([^\/?#]+)/;