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