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