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