Merge branch 'bug7141' of http://github.com/csnover/jquery into csnover-bug7141
[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|DELETE)$/,
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                 var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
199                         jsonp, status, data, type = s.type.toUpperCase(), noContent = rnoContent.test(type);
200
201                 s.url = s.url.replace( rhash, "" );
202
203                 // Use original (not extended) context object if it was provided
204                 s.context = origSettings && origSettings.context != null ? origSettings.context : s;
205
206                 // convert data if not already a string
207                 if ( s.data && s.processData && typeof s.data !== "string" ) {
208                         s.data = jQuery.param( s.data, s.traditional );
209                 }
210
211                 // Handle JSONP Parameter Callbacks
212                 if ( s.dataType === "jsonp" ) {
213                         if ( type === "GET" ) {
214                                 if ( !jsre.test( s.url ) ) {
215                                         s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
216                                 }
217                         } else if ( !s.data || !jsre.test(s.data) ) {
218                                 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
219                         }
220                         s.dataType = "json";
221                 }
222
223                 // Build temporary JSONP function
224                 if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
225                         jsonp = s.jsonpCallback || ("jsonp" + jsc++);
226
227                         // Replace the =? sequence both in the query string and the data
228                         if ( s.data ) {
229                                 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
230                         }
231
232                         s.url = s.url.replace(jsre, "=" + jsonp + "$1");
233
234                         // We need to make sure
235                         // that a JSONP style response is executed properly
236                         s.dataType = "script";
237
238                         // Handle JSONP-style loading
239                         var customJsonp = window[ jsonp ];
240
241                         window[ jsonp ] = function( tmp ) {
242                                 data = tmp;
243                                 jQuery.ajax.handleSuccess( s, xhr, status, data );
244                                 jQuery.ajax.handleComplete( s, xhr, status, data );
245                                 
246                                 if ( jQuery.isFunction( customJsonp ) ) {
247                                         customJsonp( tmp );
248
249                                 } else {
250                                         // Garbage collect
251                                         window[ jsonp ] = undefined;
252
253                                         try {
254                                                 delete window[ jsonp ];
255                                         } catch( jsonpError ) {}
256                                 }
257                                 
258                                 if ( head ) {
259                                         head.removeChild( script );
260                                 }
261                         };
262                 }
263
264                 if ( s.dataType === "script" && s.cache === null ) {
265                         s.cache = false;
266                 }
267
268                 if ( s.cache === false && type === "GET" ) {
269                         var ts = jQuery.now();
270
271                         // try replacing _= if it is there
272                         var ret = s.url.replace(rts, "$1_=" + ts);
273
274                         // if nothing was replaced, add timestamp to the end
275                         s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
276                 }
277
278                 // If data is available, append data to url for get requests
279                 if ( s.data && type === "GET" ) {
280                         s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
281                 }
282
283                 // Watch for a new set of requests
284                 if ( s.global && jQuery.ajax.active++ === 0 ) {
285                         jQuery.event.trigger( "ajaxStart" );
286                 }
287
288                 // Matches an absolute URL, and saves the domain
289                 var parts = rurl.exec( s.url ),
290                         remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
291
292                 // If we're requesting a remote document
293                 // and trying to load JSON or Script with a GET
294                 if ( s.dataType === "script" && type === "GET" && remote ) {
295                         var head = document.getElementsByTagName("head")[0] || document.documentElement;
296                         var script = document.createElement("script");
297                         if ( s.scriptCharset ) {
298                                 script.charset = s.scriptCharset;
299                         }
300                         script.src = s.url;
301
302                         // Handle Script loading
303                         if ( !jsonp ) {
304                                 var done = false;
305
306                                 // Attach handlers for all browsers
307                                 script.onload = script.onreadystatechange = function() {
308                                         if ( !done && (!this.readyState ||
309                                                         this.readyState === "loaded" || this.readyState === "complete") ) {
310                                                 done = true;
311                                                 jQuery.ajax.handleSuccess( s, xhr, status, data );
312                                                 jQuery.ajax.handleComplete( s, xhr, status, data );
313
314                                                 // Handle memory leak in IE
315                                                 script.onload = script.onreadystatechange = null;
316                                                 if ( head && script.parentNode ) {
317                                                         head.removeChild( script );
318                                                 }
319                                         }
320                                 };
321                         }
322
323                         // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
324                         // This arises when a base node is used (#2709 and #4378).
325                         head.insertBefore( script, head.firstChild );
326
327                         // We handle everything using the script element injection
328                         return undefined;
329                 }
330
331                 var requestDone = false;
332
333                 // Create the request object
334                 var xhr = s.xhr();
335
336                 if ( !xhr ) {
337                         return;
338                 }
339
340                 // Open the socket
341                 // Passing null username, generates a login popup on Opera (#2865)
342                 if ( s.username ) {
343                         xhr.open(type, s.url, s.async, s.username, s.password);
344                 } else {
345                         xhr.open(type, s.url, s.async);
346                 }
347
348                 // Need an extra try/catch for cross domain requests in Firefox 3
349                 try {
350                         // Set content-type if data specified and content-body is valid for this type
351                         if ( (s.data != null && !noContent) || (origSettings && origSettings.contentType) ) {
352                                 xhr.setRequestHeader("Content-Type", s.contentType);
353                         }
354
355                         // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
356                         if ( s.ifModified ) {
357                                 if ( jQuery.lastModified[s.url] ) {
358                                         xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
359                                 }
360
361                                 if ( jQuery.ajax.etag[s.url] ) {
362                                         xhr.setRequestHeader("If-None-Match", jQuery.ajax.etag[s.url]);
363                                 }
364                         }
365
366                         // Set header so the called script knows that it's an XMLHttpRequest
367                         // Only send the header if it's not a remote XHR
368                         if ( !remote ) {
369                                 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
370                         }
371
372                         // Set the Accepts header for the server, depending on the dataType
373                         xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
374                                 s.accepts[ s.dataType ] + ", */*; q=0.01" :
375                                 s.accepts._default );
376                 } catch( headerError ) {}
377
378                 // Allow custom headers/mimetypes and early abort
379                 if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
380                         // Handle the global AJAX counter
381                         if ( s.global && jQuery.ajax.active-- === 1 ) {
382                                 jQuery.event.trigger( "ajaxStop" );
383                         }
384
385                         // close opended socket
386                         xhr.abort();
387                         return false;
388                 }
389
390                 if ( s.global ) {
391                         jQuery.ajax.triggerGlobal( s, "ajaxSend", [xhr, s] );
392                 }
393
394                 // Wait for a response to come back
395                 var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
396                         // The request was aborted
397                         if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
398                                 // Opera doesn't call onreadystatechange before this point
399                                 // so we simulate the call
400                                 if ( !requestDone ) {
401                                         jQuery.ajax.handleComplete( s, xhr, status, data );
402                                 }
403
404                                 requestDone = true;
405                                 if ( xhr ) {
406                                         xhr.onreadystatechange = jQuery.noop;
407                                 }
408
409                         // The transfer is complete and the data is available, or the request timed out
410                         } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
411                                 requestDone = true;
412                                 xhr.onreadystatechange = jQuery.noop;
413
414                                 status = isTimeout === "timeout" ?
415                                         "timeout" :
416                                         !jQuery.ajax.httpSuccess( xhr ) ?
417                                                 "error" :
418                                                 s.ifModified && jQuery.ajax.httpNotModified( xhr, s.url ) ?
419                                                         "notmodified" :
420                                                         "success";
421
422                                 var errMsg;
423
424                                 if ( status === "success" ) {
425                                         // Watch for, and catch, XML document parse errors
426                                         try {
427                                                 // process the data (runs the xml through httpData regardless of callback)
428                                                 data = jQuery.ajax.httpData( xhr, s.dataType, s );
429                                         } catch( parserError ) {
430                                                 status = "parsererror";
431                                                 errMsg = parserError;
432                                         }
433                                 }
434
435                                 // Make sure that the request was successful or notmodified
436                                 if ( status === "success" || status === "notmodified" ) {
437                                         // JSONP handles its own success callback
438                                         if ( !jsonp ) {
439                                                 jQuery.ajax.handleSuccess( s, xhr, status, data );
440                                         }
441                                 } else {
442                                         jQuery.ajax.handleError( s, xhr, status, errMsg );
443                                 }
444
445                                 // Fire the complete handlers
446                                 if ( !jsonp ) {
447                                         jQuery.ajax.handleComplete( s, xhr, status, data );
448                                 }
449
450                                 if ( isTimeout === "timeout" ) {
451                                         xhr.abort();
452                                 }
453
454                                 // Stop memory leaks
455                                 if ( s.async ) {
456                                         xhr = null;
457                                 }
458                         }
459                 };
460
461                 // Override the abort handler, if we can (IE 6 doesn't allow it, but that's OK)
462                 // Opera doesn't fire onreadystatechange at all on abort
463                 try {
464                         var oldAbort = xhr.abort;
465                         xhr.abort = function() {
466                                 // xhr.abort in IE7 is not a native JS function
467                                 // and does not have a call property
468                                 if ( xhr && oldAbort.call ) {
469                                         oldAbort.call( xhr );
470                                 }
471
472                                 onreadystatechange( "abort" );
473                         };
474                 } catch( abortError ) {}
475
476                 // Timeout checker
477                 if ( s.async && s.timeout > 0 ) {
478                         setTimeout(function() {
479                                 // Check to see if the request is still happening
480                                 if ( xhr && !requestDone ) {
481                                         onreadystatechange( "timeout" );
482                                 }
483                         }, s.timeout);
484                 }
485
486                 // Send the data
487                 try {
488                         xhr.send( noContent || s.data == null ? null : s.data );
489
490                 } catch( sendError ) {
491                         jQuery.ajax.handleError( s, xhr, null, sendError );
492
493                         // Fire the complete handlers
494                         jQuery.ajax.handleComplete( s, xhr, status, data );
495                 }
496
497                 // firefox 1.5 doesn't fire statechange for sync requests
498                 if ( !s.async ) {
499                         onreadystatechange();
500                 }
501
502                 // return XMLHttpRequest to allow aborting the request etc.
503                 return xhr;
504         },
505
506         // Serialize an array of form elements or a set of
507         // key/values into a query string
508         param: function( a, traditional ) {
509                 var s = [], add = function( key, value ) {
510                         // If value is a function, invoke it and return its value
511                         value = jQuery.isFunction(value) ? value() : value;
512                         s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
513                 };
514                 
515                 // Set traditional to true for jQuery <= 1.3.2 behavior.
516                 if ( traditional === undefined ) {
517                         traditional = jQuery.ajaxSettings.traditional;
518                 }
519                 
520                 // If an array was passed in, assume that it is an array of form elements.
521                 if ( jQuery.isArray(a) || a.jquery ) {
522                         // Serialize the form elements
523                         jQuery.each( a, function() {
524                                 add( this.name, this.value );
525                         });
526                         
527                 } else {
528                         // If traditional, encode the "old" way (the way 1.3.2 or older
529                         // did it), otherwise encode params recursively.
530                         for ( var prefix in a ) {
531                                 buildParams( prefix, a[prefix], traditional, add );
532                         }
533                 }
534
535                 // Return the resulting serialization
536                 return s.join("&").replace(r20, "+");
537         }
538 });
539
540 function buildParams( prefix, obj, traditional, add ) {
541         if ( jQuery.isArray(obj) && obj.length ) {
542                 // Serialize array item.
543                 jQuery.each( obj, function( i, v ) {
544                         if ( traditional || rbracket.test( prefix ) ) {
545                                 // Treat each array item as a scalar.
546                                 add( prefix, v );
547
548                         } else {
549                                 // If array item is non-scalar (array or object), encode its
550                                 // numeric index to resolve deserialization ambiguity issues.
551                                 // Note that rack (as of 1.0.0) can't currently deserialize
552                                 // nested arrays properly, and attempting to do so may cause
553                                 // a server error. Possible fixes are to modify rack's
554                                 // deserialization algorithm or to provide an option or flag
555                                 // to force array serialization to be shallow.
556                                 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
557                         }
558                 });
559                         
560         } else if ( !traditional && obj != null && typeof obj === "object" ) {
561                 if ( jQuery.isEmptyObject( obj ) ) {
562                         add( prefix, "" );
563
564                 // Serialize object item.
565                 } else {
566                         jQuery.each( obj, function( k, v ) {
567                                 buildParams( prefix + "[" + k + "]", v, traditional, add );
568                         });
569                 }
570                                         
571         } else {
572                 // Serialize scalar item.
573                 add( prefix, obj );
574         }
575 }
576
577 jQuery.extend( jQuery.ajax, {
578
579         // Counter for holding the number of active queries
580         active: 0,
581
582         // Last-Modified header cache for next request
583         lastModified: {},
584         etag: {},
585
586         handleError: function( s, xhr, status, e ) {
587                 // If a local callback was specified, fire it
588                 if ( s.error ) {
589                         s.error.call( s.context, xhr, status, e );
590                 }
591
592                 // Fire the global callback
593                 if ( s.global ) {
594                         jQuery.ajax.triggerGlobal( s, "ajaxError", [xhr, s, e] );
595                 }
596         },
597
598         handleSuccess: function( s, xhr, status, data ) {
599                 // If a local callback was specified, fire it and pass it the data
600                 if ( s.success ) {
601                         s.success.call( s.context, data, status, xhr );
602                 }
603
604                 // Fire the global callback
605                 if ( s.global ) {
606                         jQuery.ajax.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
607                 }
608         },
609
610         handleComplete: function( s, xhr, status ) {
611                 // Process result
612                 if ( s.complete ) {
613                         s.complete.call( s.context, xhr, status );
614                 }
615
616                 // The request was completed
617                 if ( s.global ) {
618                         jQuery.ajax.triggerGlobal( s, "ajaxComplete", [xhr, s] );
619                 }
620
621                 // Handle the global AJAX counter
622                 if ( s.global && jQuery.ajax.active-- === 1 ) {
623                         jQuery.event.trigger( "ajaxStop" );
624                 }
625         },
626                 
627         triggerGlobal: function( s, type, args ) {
628                 (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
629         },
630
631         // Determines if an XMLHttpRequest was successful or not
632         httpSuccess: function( xhr ) {
633                 try {
634                         // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
635                         return !xhr.status && location.protocol === "file:" ||
636                                 xhr.status >= 200 && xhr.status < 300 ||
637                                 xhr.status === 304 || xhr.status === 1223;
638                 } catch(e) {}
639
640                 return false;
641         },
642
643         // Determines if an XMLHttpRequest returns NotModified
644         httpNotModified: function( xhr, url ) {
645                 var lastModified = xhr.getResponseHeader("Last-Modified"),
646                         etag = xhr.getResponseHeader("Etag");
647
648                 if ( lastModified ) {
649                         jQuery.ajax.lastModified[url] = lastModified;
650                 }
651
652                 if ( etag ) {
653                         jQuery.ajax.etag[url] = etag;
654                 }
655
656                 return xhr.status === 304;
657         },
658
659         httpData: function( xhr, type, s ) {
660                 var ct = xhr.getResponseHeader("content-type") || "",
661                         xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
662                         data = xml ? xhr.responseXML : xhr.responseText;
663
664                 if ( xml && data.documentElement.nodeName === "parsererror" ) {
665                         jQuery.error( "parsererror" );
666                 }
667
668                 // Allow a pre-filtering function to sanitize the response
669                 // s is checked to keep backwards compatibility
670                 if ( s && s.dataFilter ) {
671                         data = s.dataFilter( data, type );
672                 }
673
674                 // The filter can actually parse the response
675                 if ( typeof data === "string" ) {
676                         // Get the JavaScript object, if JSON is used.
677                         if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
678                                 data = jQuery.parseJSON( data );
679
680                         // If the type is "script", eval it in global context
681                         } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
682                                 jQuery.globalEval( data );
683                         }
684                 }
685
686                 return data;
687         }
688
689 });
690
691 /*
692  * Create the request object; Microsoft failed to properly
693  * implement the XMLHttpRequest in IE7 (can't request local files),
694  * so we use the ActiveXObject when it is available
695  * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
696  * we need a fallback.
697  */
698 if ( window.ActiveXObject ) {
699         jQuery.ajaxSettings.xhr = function() {
700                 if ( window.location.protocol !== "file:" ) {
701                         try {
702                                 return new window.XMLHttpRequest();
703                         } catch(xhrError) {}
704                 }
705
706                 try {
707                         return new window.ActiveXObject("Microsoft.XMLHTTP");
708                 } catch(activeError) {}
709         };
710 }
711
712 // Does this browser support XHR requests?
713 jQuery.support.ajax = !!jQuery.ajaxSettings.xhr();
714
715 // For backwards compatibility
716 jQuery.extend( jQuery.ajax );
717
718 })( jQuery );