For JSON and script requests, set the scriptCharset before the url so IE won't interp...
[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                 s.context = origSettings && origSettings.context || s;
211
212                 // convert data if not already a string
213                 if ( s.data && s.processData && typeof s.data !== "string" ) {
214                         s.data = jQuery.param( s.data, s.traditional );
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                                 data = tmp;
249                                 jQuery.ajax.handleSuccess( s, xhr, status, data );
250                                 jQuery.ajax.handleComplete( s, xhr, status, data );
251                                 
252                                 if ( jQuery.isFunction( customJsonp ) ) {
253                                         customJsonp( tmp );
254
255                                 } else {
256                                         // Garbage collect
257                                         window[ jsonp ] = undefined;
258
259                                         try {
260                                                 delete window[ jsonp ];
261                                         } catch( jsonpError ) {}
262                                 }
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 && type === "GET" ) {
275                         var ts = jQuery.now();
276
277                         // try replacing _= if it is there
278                         var ret = s.url.replace(rts, "$1_=" + ts + "$2");
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 requests
285                 if ( s.data && type === "GET" ) {
286                         s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
287                 }
288
289                 // Watch for a new set of requests
290                 if ( s.global && jQuery.ajax.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] !== location.protocol || parts[2] !== 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.ajax.handleSuccess( s, xhr, status, data );
318                                                 jQuery.ajax.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 the correct header, if data is being sent
357                         if ( s.data || 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.ajax.etag[s.url] ) {
368                                         xhr.setRequestHeader("If-None-Match", jQuery.ajax.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.ajax.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.ajax.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.ajax.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.ajax.httpSuccess( xhr ) ?
423                                                 "error" :
424                                                 s.ifModified && jQuery.ajax.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.ajax.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.ajax.handleSuccess( s, xhr, status, data );
446                                         }
447                                 } else {
448                                         jQuery.ajax.handleError( s, xhr, status, errMsg );
449                                 }
450
451                                 // Fire the complete handlers
452                                 if ( !jsonp ) {
453                                         jQuery.ajax.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 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                                 if ( xhr ) {
473                                         oldAbort.call( xhr );
474                                 }
475
476                                 onreadystatechange( "abort" );
477                         };
478                 } catch( abortError ) {}
479
480                 // Timeout checker
481                 if ( s.async && s.timeout > 0 ) {
482                         setTimeout(function() {
483                                 // Check to see if the request is still happening
484                                 if ( xhr && !requestDone ) {
485                                         onreadystatechange( "timeout" );
486                                 }
487                         }, s.timeout);
488                 }
489
490                 // Send the data
491                 try {
492                         xhr.send( (type !== "GET" && s.data) || null );
493
494                 } catch( sendError ) {
495                         jQuery.ajax.handleError( s, xhr, null, e );
496
497                         // Fire the complete handlers
498                         jQuery.ajax.handleComplete( s, xhr, status, data );
499                 }
500
501                 // firefox 1.5 doesn't fire statechange for sync requests
502                 if ( !s.async ) {
503                         onreadystatechange();
504                 }
505
506                 // return XMLHttpRequest to allow aborting the request etc.
507                 return xhr;
508         },
509
510         // Serialize an array of form elements or a set of
511         // key/values into a query string
512         param: function( a, traditional ) {
513                 var s = [], add = function( key, value ) {
514                         // If value is a function, invoke it and return its value
515                         value = jQuery.isFunction(value) ? value() : value;
516                         s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
517                 };
518                 
519                 // Set traditional to true for jQuery <= 1.3.2 behavior.
520                 if ( traditional === undefined ) {
521                         traditional = jQuery.ajaxSettings.traditional;
522                 }
523                 
524                 // If an array was passed in, assume that it is an array of form elements.
525                 if ( jQuery.isArray(a) || a.jquery ) {
526                         // Serialize the form elements
527                         jQuery.each( a, function() {
528                                 add( this.name, this.value );
529                         });
530                         
531                 } else {
532                         // If traditional, encode the "old" way (the way 1.3.2 or older
533                         // did it), otherwise encode params recursively.
534                         for ( var prefix in a ) {
535                                 buildParams( prefix, a[prefix], traditional, add );
536                         }
537                 }
538
539                 // Return the resulting serialization
540                 return s.join("&").replace(r20, "+");
541         }
542 });
543
544 function buildParams( prefix, obj, traditional, add ) {
545         if ( jQuery.isArray(obj) && obj.length ) {
546                 // Serialize array item.
547                 jQuery.each( obj, function( i, v ) {
548                         if ( traditional || rbracket.test( prefix ) ) {
549                                 // Treat each array item as a scalar.
550                                 add( prefix, v );
551
552                         } else {
553                                 // If array item is non-scalar (array or object), encode its
554                                 // numeric index to resolve deserialization ambiguity issues.
555                                 // Note that rack (as of 1.0.0) can't currently deserialize
556                                 // nested arrays properly, and attempting to do so may cause
557                                 // a server error. Possible fixes are to modify rack's
558                                 // deserialization algorithm or to provide an option or flag
559                                 // to force array serialization to be shallow.
560                                 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
561                         }
562                 });
563                         
564         } else if ( !traditional && obj != null && typeof obj === "object" ) {
565                 if ( jQuery.isEmptyObject( obj ) ) {
566                         add( prefix, "" );
567
568                 // Serialize object item.
569                 } else {
570                         jQuery.each( obj, function( k, v ) {
571                                 buildParams( prefix + "[" + k + "]", v, traditional, add );
572                         });
573                 }
574                                         
575         } else {
576                 // Serialize scalar item.
577                 add( prefix, obj );
578         }
579 }
580
581 jQuery.extend( jQuery.ajax, {
582
583         // Counter for holding the number of active queries
584         active: 0,
585
586         // Last-Modified header cache for next request
587         lastModified: {},
588         etag: {},
589
590         handleError: function( s, xhr, status, e ) {
591                 // If a local callback was specified, fire it
592                 if ( s.error ) {
593                         s.error.call( s.context, xhr, status, e );
594                 }
595
596                 // Fire the global callback
597                 if ( s.global ) {
598                         jQuery.ajax.triggerGlobal( s, "ajaxError", [xhr, s, e] );
599                 }
600         },
601
602         handleSuccess: function( s, xhr, status, data ) {
603                 // If a local callback was specified, fire it and pass it the data
604                 if ( s.success ) {
605                         s.success.call( s.context, data, status, xhr );
606                 }
607
608                 // Fire the global callback
609                 if ( s.global ) {
610                         jQuery.ajax.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
611                 }
612         },
613
614         handleComplete: function( s, xhr, status ) {
615                 // Process result
616                 if ( s.complete ) {
617                         s.complete.call( s.context, xhr, status );
618                 }
619
620                 // The request was completed
621                 if ( s.global ) {
622                         jQuery.ajax.triggerGlobal( s, "ajaxComplete", [xhr, s] );
623                 }
624
625                 // Handle the global AJAX counter
626                 if ( s.global && jQuery.ajax.active-- === 1 ) {
627                         jQuery.event.trigger( "ajaxStop" );
628                 }
629         },
630                 
631         triggerGlobal: function( s, type, args ) {
632                 (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
633         },
634
635         // Determines if an XMLHttpRequest was successful or not
636         httpSuccess: function( xhr ) {
637                 try {
638                         // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
639                         return !xhr.status && location.protocol === "file:" ||
640                                 xhr.status >= 200 && xhr.status < 300 ||
641                                 xhr.status === 304 || xhr.status === 1223;
642                 } catch(e) {}
643
644                 return false;
645         },
646
647         // Determines if an XMLHttpRequest returns NotModified
648         httpNotModified: function( xhr, url ) {
649                 var lastModified = xhr.getResponseHeader("Last-Modified"),
650                         etag = xhr.getResponseHeader("Etag");
651
652                 if ( lastModified ) {
653                         jQuery.ajax.lastModified[url] = lastModified;
654                 }
655
656                 if ( etag ) {
657                         jQuery.ajax.etag[url] = etag;
658                 }
659
660                 return xhr.status === 304;
661         },
662
663         httpData: function( xhr, type, s ) {
664                 var ct = xhr.getResponseHeader("content-type") || "",
665                         xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
666                         data = xml ? xhr.responseXML : xhr.responseText;
667
668                 if ( xml && data.documentElement.nodeName === "parsererror" ) {
669                         jQuery.error( "parsererror" );
670                 }
671
672                 // Allow a pre-filtering function to sanitize the response
673                 // s is checked to keep backwards compatibility
674                 if ( s && s.dataFilter ) {
675                         data = s.dataFilter( data, type );
676                 }
677
678                 // The filter can actually parse the response
679                 if ( typeof data === "string" ) {
680                         // Get the JavaScript object, if JSON is used.
681                         if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
682                                 data = jQuery.parseJSON( data );
683
684                         // If the type is "script", eval it in global context
685                         } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
686                                 jQuery.globalEval( data );
687                         }
688                 }
689
690                 return data;
691         }
692
693 });
694
695 // Does this browser support XHR requests?
696 jQuery.support.ajax = !!jQuery.ajaxSettings.xhr();
697
698 // For backwards compatibility
699 jQuery.extend( jQuery.ajax );
700
701 })( jQuery );