Merge branch 'jquerymaster' of http://github.com/SlexAxton/jquery into SlexAxton...
[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                 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                 // If the jsonpCallback has been set, we can assume that dataType is jsonp
212                 // Ticket #5803
213                 if ( s.jsonpCallback ) {
214                   s.dataType = "jsonp";
215                 }
216
217                 // Handle JSONP Parameter Callbacks
218                 if ( s.dataType === "jsonp" ) {
219                         if ( type === "GET" ) {
220                                 if ( !jsre.test( s.url ) ) {
221                                         s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
222                                 }
223                         } else if ( !s.data || !jsre.test(s.data) ) {
224                                 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
225                         }
226                         s.dataType = "json";
227                 }
228
229                 // Build temporary JSONP function
230                 if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
231                         jsonp = s.jsonpCallback || ("jsonp" + jsc++);
232
233                         // Replace the =? sequence both in the query string and the data
234                         if ( s.data ) {
235                                 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
236                         }
237
238                         s.url = s.url.replace(jsre, "=" + jsonp + "$1");
239
240                         // We need to make sure
241                         // that a JSONP style response is executed properly
242                         s.dataType = "script";
243
244                         // Handle JSONP-style loading
245                         var customJsonp = window[ jsonp ];
246
247                         window[ jsonp ] = function( tmp ) {
248                                 if ( jQuery.isFunction( customJsonp ) ) {
249                                         customJsonp( tmp );
250
251                                 } else {
252                                         // Garbage collect
253                                         window[ jsonp ] = undefined;
254
255                                         try {
256                                                 delete window[ jsonp ];
257                                         } catch( jsonpError ) {}
258                                 }
259
260                                 data = tmp;
261                                 jQuery.handleSuccess( s, xhr, status, data );
262                                 jQuery.handleComplete( s, xhr, status, data );
263                                 
264                                 if ( head ) {
265                                         head.removeChild( script );
266                                 }
267                         };
268                 }
269
270                 if ( s.dataType === "script" && s.cache === null ) {
271                         s.cache = false;
272                 }
273
274                 if ( s.cache === false && noContent ) {
275                         var ts = jQuery.now();
276
277                         // try replacing _= if it is there
278                         var ret = s.url.replace(rts, "$1_=" + ts);
279
280                         // if nothing was replaced, add timestamp to the end
281                         s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
282                 }
283
284                 // If data is available, append data to url for GET/HEAD requests
285                 if ( s.data && noContent ) {
286                         s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
287                 }
288
289                 // Watch for a new set of requests
290                 if ( s.global && jQuery.active++ === 0 ) {
291                         jQuery.event.trigger( "ajaxStart" );
292                 }
293
294                 // Matches an absolute URL, and saves the domain
295                 var parts = rurl.exec( s.url ),
296                         remote = parts && (parts[1] && parts[1].toLowerCase() !== location.protocol || parts[2].toLowerCase() !== location.host);
297
298                 // If we're requesting a remote document
299                 // and trying to load JSON or Script with a GET
300                 if ( s.dataType === "script" && type === "GET" && remote ) {
301                         var head = document.getElementsByTagName("head")[0] || document.documentElement;
302                         var script = document.createElement("script");
303                         if ( s.scriptCharset ) {
304                                 script.charset = s.scriptCharset;
305                         }
306                         script.src = s.url;
307
308                         // Handle Script loading
309                         if ( !jsonp ) {
310                                 var done = false;
311
312                                 // Attach handlers for all browsers
313                                 script.onload = script.onreadystatechange = function() {
314                                         if ( !done && (!this.readyState ||
315                                                         this.readyState === "loaded" || this.readyState === "complete") ) {
316                                                 done = true;
317                                                 jQuery.handleSuccess( s, xhr, status, data );
318                                                 jQuery.handleComplete( s, xhr, status, data );
319
320                                                 // Handle memory leak in IE
321                                                 script.onload = script.onreadystatechange = null;
322                                                 if ( head && script.parentNode ) {
323                                                         head.removeChild( script );
324                                                 }
325                                         }
326                                 };
327                         }
328
329                         // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
330                         // This arises when a base node is used (#2709 and #4378).
331                         head.insertBefore( script, head.firstChild );
332
333                         // We handle everything using the script element injection
334                         return undefined;
335                 }
336
337                 var requestDone = false;
338
339                 // Create the request object
340                 var xhr = s.xhr();
341
342                 if ( !xhr ) {
343                         return;
344                 }
345
346                 // Open the socket
347                 // Passing null username, generates a login popup on Opera (#2865)
348                 if ( s.username ) {
349                         xhr.open(type, s.url, s.async, s.username, s.password);
350                 } else {
351                         xhr.open(type, s.url, s.async);
352                 }
353
354                 // Need an extra try/catch for cross domain requests in Firefox 3
355                 try {
356                         // Set content-type if data specified and content-body is valid for this type
357                         if ( (s.data != null && !noContent) || (origSettings && origSettings.contentType) ) {
358                                 xhr.setRequestHeader("Content-Type", s.contentType);
359                         }
360
361                         // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
362                         if ( s.ifModified ) {
363                                 if ( jQuery.lastModified[s.url] ) {
364                                         xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
365                                 }
366
367                                 if ( jQuery.etag[s.url] ) {
368                                         xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
369                                 }
370                         }
371
372                         // Set header so the called script knows that it's an XMLHttpRequest
373                         // Only send the header if it's not a remote XHR
374                         if ( !remote ) {
375                                 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
376                         }
377
378                         // Set the Accepts header for the server, depending on the dataType
379                         xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
380                                 s.accepts[ s.dataType ] + ", */*; q=0.01" :
381                                 s.accepts._default );
382                 } catch( headerError ) {}
383
384                 // Allow custom headers/mimetypes and early abort
385                 if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
386                         // Handle the global AJAX counter
387                         if ( s.global && jQuery.active-- === 1 ) {
388                                 jQuery.event.trigger( "ajaxStop" );
389                         }
390
391                         // close opended socket
392                         xhr.abort();
393                         return false;
394                 }
395
396                 if ( s.global ) {
397                         jQuery.triggerGlobal( s, "ajaxSend", [xhr, s] );
398                 }
399
400                 // Wait for a response to come back
401                 var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
402                         // The request was aborted
403                         if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
404                                 // Opera doesn't call onreadystatechange before this point
405                                 // so we simulate the call
406                                 if ( !requestDone ) {
407                                         jQuery.handleComplete( s, xhr, status, data );
408                                 }
409
410                                 requestDone = true;
411                                 if ( xhr ) {
412                                         xhr.onreadystatechange = jQuery.noop;
413                                 }
414
415                         // The transfer is complete and the data is available, or the request timed out
416                         } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
417                                 requestDone = true;
418                                 xhr.onreadystatechange = jQuery.noop;
419
420                                 status = isTimeout === "timeout" ?
421                                         "timeout" :
422                                         !jQuery.httpSuccess( xhr ) ?
423                                                 "error" :
424                                                 s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
425                                                         "notmodified" :
426                                                         "success";
427
428                                 var errMsg;
429
430                                 if ( status === "success" ) {
431                                         // Watch for, and catch, XML document parse errors
432                                         try {
433                                                 // process the data (runs the xml through httpData regardless of callback)
434                                                 data = jQuery.httpData( xhr, s.dataType, s );
435                                         } catch( parserError ) {
436                                                 status = "parsererror";
437                                                 errMsg = parserError;
438                                         }
439                                 }
440
441                                 // Make sure that the request was successful or notmodified
442                                 if ( status === "success" || status === "notmodified" ) {
443                                         // JSONP handles its own success callback
444                                         if ( !jsonp ) {
445                                                 jQuery.handleSuccess( s, xhr, status, data );
446                                         }
447                                 } else {
448                                         jQuery.handleError( s, xhr, status, errMsg );
449                                 }
450
451                                 // Fire the complete handlers
452                                 if ( !jsonp ) {
453                                         jQuery.handleComplete( s, xhr, status, data );
454                                 }
455
456                                 if ( isTimeout === "timeout" ) {
457                                         xhr.abort();
458                                 }
459
460                                 // Stop memory leaks
461                                 if ( s.async ) {
462                                         xhr = null;
463                                 }
464                         }
465                 };
466
467                 // Override the abort handler, if we can (IE 6 doesn't allow it, but that's OK)
468                 // Opera doesn't fire onreadystatechange at all on abort
469                 try {
470                         var oldAbort = xhr.abort;
471                         xhr.abort = function() {
472                                 // xhr.abort in IE7 is not a native JS function
473                                 // and does not have a call property
474                                 if ( xhr && oldAbort.call ) {
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( noContent || s.data == null ? null : s.data );
495
496                 } catch( sendError ) {
497                         jQuery.handleError( s, xhr, null, sendError );
498
499                         // Fire the complete handlers
500                         jQuery.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 // This is still on the jQuery object... for now
584 // Want to move this to jQuery.ajax some day
585 jQuery.extend({
586
587         // Counter for holding the number of active queries
588         active: 0,
589
590         // Last-Modified header cache for next request
591         lastModified: {},
592         etag: {},
593
594         handleError: function( s, xhr, status, e ) {
595                 // If a local callback was specified, fire it
596                 if ( s.error ) {
597                         s.error.call( s.context, xhr, status, e );
598                 }
599
600                 // Fire the global callback
601                 if ( s.global ) {
602                         jQuery.triggerGlobal( s, "ajaxError", [xhr, s, e] );
603                 }
604         },
605
606         handleSuccess: function( s, xhr, status, data ) {
607                 // If a local callback was specified, fire it and pass it the data
608                 if ( s.success ) {
609                         s.success.call( s.context, data, status, xhr );
610                 }
611
612                 // Fire the global callback
613                 if ( s.global ) {
614                         jQuery.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
615                 }
616         },
617
618         handleComplete: function( s, xhr, status ) {
619                 // Process result
620                 if ( s.complete ) {
621                         s.complete.call( s.context, xhr, status );
622                 }
623
624                 // The request was completed
625                 if ( s.global ) {
626                         jQuery.triggerGlobal( s, "ajaxComplete", [xhr, s] );
627                 }
628
629                 // Handle the global AJAX counter
630                 if ( s.global && jQuery.active-- === 1 ) {
631                         jQuery.event.trigger( "ajaxStop" );
632                 }
633         },
634                 
635         triggerGlobal: function( s, type, args ) {
636                 (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
637         },
638
639         // Determines if an XMLHttpRequest was successful or not
640         httpSuccess: function( xhr ) {
641                 try {
642                         // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
643                         return !xhr.status && location.protocol === "file:" ||
644                                 xhr.status >= 200 && xhr.status < 300 ||
645                                 xhr.status === 304 || xhr.status === 1223;
646                 } catch(e) {}
647
648                 return false;
649         },
650
651         // Determines if an XMLHttpRequest returns NotModified
652         httpNotModified: function( xhr, url ) {
653                 var lastModified = xhr.getResponseHeader("Last-Modified"),
654                         etag = xhr.getResponseHeader("Etag");
655
656                 if ( lastModified ) {
657                         jQuery.lastModified[url] = lastModified;
658                 }
659
660                 if ( etag ) {
661                         jQuery.etag[url] = etag;
662                 }
663
664                 return xhr.status === 304;
665         },
666
667         httpData: function( xhr, type, s ) {
668                 var ct = xhr.getResponseHeader("content-type") || "",
669                         xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
670                         data = xml ? xhr.responseXML : xhr.responseText;
671
672                 if ( xml && data.documentElement.nodeName === "parsererror" ) {
673                         jQuery.error( "parsererror" );
674                 }
675
676                 // Allow a pre-filtering function to sanitize the response
677                 // s is checked to keep backwards compatibility
678                 if ( s && s.dataFilter ) {
679                         data = s.dataFilter( data, type );
680                 }
681
682                 // The filter can actually parse the response
683                 if ( typeof data === "string" ) {
684                         // Get the JavaScript object, if JSON is used.
685                         if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
686                                 data = jQuery.parseJSON( data );
687
688                         // If the type is "script", eval it in global context
689                         } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
690                                 jQuery.globalEval( data );
691                         }
692                 }
693
694                 return data;
695         }
696
697 });
698
699 /*
700  * Create the request object; Microsoft failed to properly
701  * implement the XMLHttpRequest in IE7 (can't request local files),
702  * so we use the ActiveXObject when it is available
703  * Additionally XMLHttpRequest can be disabled in IE7/IE8 so
704  * we need a fallback.
705  */
706 if ( window.ActiveXObject ) {
707         jQuery.ajaxSettings.xhr = function() {
708                 if ( window.location.protocol !== "file:" ) {
709                         try {
710                                 return new window.XMLHttpRequest();
711                         } catch(xhrError) {}
712                 }
713
714                 try {
715                         return new window.ActiveXObject("Microsoft.XMLHTTP");
716                 } catch(activeError) {}
717         };
718 }
719
720 // Does this browser support XHR requests?
721 jQuery.support.ajax = !!jQuery.ajaxSettings.xhr();
722
723 })( jQuery );