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