Moved from the old JSMin to using YUIMin for compressing the jQuery source. Additiona...
[jquery.git] / src / ajax.js
1 jQuery.fn.extend({
2         // Keep a copy of the old load
3         _load: jQuery.fn.load,
4
5         load: function( url, params, callback ) {
6                 if ( typeof url !== "string" )
7                         return this._load( url );
8
9                 var off = url.indexOf(" ");
10                 if ( off >= 0 ) {
11                         var selector = url.slice(off, url.length);
12                         url = url.slice(0, off);
13                 }
14
15                 // Default to a GET request
16                 var type = "GET";
17
18                 // If the second parameter was provided
19                 if ( params )
20                         // If it's a function
21                         if ( jQuery.isFunction( params ) ) {
22                                 // We assume that it's the callback
23                                 callback = params;
24                                 params = null;
25
26                         // Otherwise, build a param string
27                         } else if( typeof params === "object" ) {
28                                 params = jQuery.param( params );
29                                 type = "POST";
30                         }
31
32                 var self = this;
33
34                 // Request the remote document
35                 jQuery.ajax({
36                         url: url,
37                         type: type,
38                         dataType: "html",
39                         data: params,
40                         complete: function(res, status){
41                                 // If successful, inject the HTML into all the matched elements
42                                 if ( status == "success" || status == "notmodified" )
43                                         // See if a selector was specified
44                                         self.html( selector ?
45                                                 // Create a dummy div to hold the results
46                                                 jQuery("<div/>")
47                                                         // inject the contents of the document in, removing the scripts
48                                                         // to avoid any 'Permission Denied' errors in IE
49                                                         .append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
50
51                                                         // Locate the specified elements
52                                                         .find(selector) :
53
54                                                 // If not, just inject the full result
55                                                 res.responseText );
56
57                                 if( callback )
58                                         self.each( callback, [res.responseText, status, res] );
59                         }
60                 });
61                 return this;
62         },
63
64         serialize: function() {
65                 return jQuery.param(this.serializeArray());
66         },
67         serializeArray: function() {
68                 return this.map(function(){
69                         return this.elements ? jQuery.makeArray(this.elements) : this;
70                 })
71                 .filter(function(){
72                         return this.name && !this.disabled &&
73                                 (this.checked || /select|textarea/i.test(this.nodeName) ||
74                                         /text|hidden|password/i.test(this.type));
75                 })
76                 .map(function(i, elem){
77                         var val = jQuery(this).val();
78                         return val == null ? null :
79                                 jQuery.isArray(val) ?
80                                         jQuery.map( val, function(val, i){
81                                                 return {name: elem.name, value: val};
82                                         }) :
83                                         {name: elem.name, value: val};
84                 }).get();
85         }
86 });
87
88 // Attach a bunch of functions for handling common AJAX events
89 jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
90         jQuery.fn[o] = function(f){
91                 return this.bind(o, f);
92         };
93 });
94
95 var jsc = now();
96
97 jQuery.extend({
98   
99         get: function( url, data, callback, type ) {
100                 // shift arguments if data argument was ommited
101                 if ( jQuery.isFunction( data ) ) {
102                         callback = data;
103                         data = null;
104                 }
105
106                 return jQuery.ajax({
107                         type: "GET",
108                         url: url,
109                         data: data,
110                         success: callback,
111                         dataType: type
112                 });
113         },
114
115         getScript: function( url, callback ) {
116                 return jQuery.get(url, null, callback, "script");
117         },
118
119         getJSON: function( url, data, callback ) {
120                 return jQuery.get(url, data, callback, "json");
121         },
122
123         post: function( url, data, callback, type ) {
124                 if ( jQuery.isFunction( data ) ) {
125                         callback = data;
126                         data = {};
127                 }
128
129                 return jQuery.ajax({
130                         type: "POST",
131                         url: url,
132                         data: data,
133                         success: callback,
134                         dataType: type
135                 });
136         },
137
138         ajaxSetup: function( settings ) {
139                 jQuery.extend( jQuery.ajaxSettings, settings );
140         },
141
142         ajaxSettings: {
143                 url: location.href,
144                 global: true,
145                 type: "GET",
146                 timeout: 0,
147                 contentType: "application/x-www-form-urlencoded",
148                 processData: true,
149                 async: true,
150                 data: null,
151                 username: null,
152                 password: null,
153                 // Create the request object; Microsoft failed to properly
154                 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
155                 // This function can be overriden by calling jQuery.ajaxSetup
156                 xhr:function(){
157                         return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
158                 },
159                 accepts: {
160                         xml: "application/xml, text/xml",
161                         html: "text/html",
162                         script: "text/javascript, application/javascript",
163                         json: "application/json, text/javascript",
164                         text: "text/plain",
165                         _default: "*/*"
166                 }
167         },
168
169         // Last-Modified header cache for next request
170         lastModified: {},
171
172         ajax: function( s ) {
173                 // Extend the settings, but re-extend 's' so that it can be
174                 // checked again later (in the test suite, specifically)
175                 s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
176
177                 var jsonp, jsre = /=\?(&|$)/g, status, data,
178                         type = s.type.toUpperCase();
179
180                 // convert data if not already a string
181                 if ( s.data && s.processData && typeof s.data !== "string" )
182                         s.data = jQuery.param(s.data);
183
184                 // Handle JSONP Parameter Callbacks
185                 if ( s.dataType == "jsonp" ) {
186                         if ( type == "GET" ) {
187                                 if ( !s.url.match(jsre) )
188                                         s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
189                         } else if ( !s.data || !s.data.match(jsre) )
190                                 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
191                         s.dataType = "json";
192                 }
193
194                 // Build temporary JSONP function
195                 if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
196                         jsonp = "jsonp" + jsc++;
197
198                         // Replace the =? sequence both in the query string and the data
199                         if ( s.data )
200                                 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
201                         s.url = s.url.replace(jsre, "=" + jsonp + "$1");
202
203                         // We need to make sure
204                         // that a JSONP style response is executed properly
205                         s.dataType = "script";
206
207                         // Handle JSONP-style loading
208                         window[ jsonp ] = function(tmp){
209                                 data = tmp;
210                                 success();
211                                 complete();
212                                 // Garbage collect
213                                 window[ jsonp ] = undefined;
214                                 try{ delete window[ jsonp ]; } catch(e){}
215                                 if ( head )
216                                         head.removeChild( script );
217                         };
218                 }
219
220                 if ( s.dataType == "script" && s.cache == null )
221                         s.cache = false;
222
223                 if ( s.cache === false && type == "GET" ) {
224                         var ts = now();
225                         // try replacing _= if it is there
226                         var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
227                         // if nothing was replaced, add timestamp to the end
228                         s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
229                 }
230
231                 // If data is available, append data to url for get requests
232                 if ( s.data && type == "GET" ) {
233                         s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;
234
235                         // IE likes to send both get and post data, prevent this
236                         s.data = null;
237                 }
238
239                 // Watch for a new set of requests
240                 if ( s.global && ! jQuery.active++ )
241                         jQuery.event.trigger( "ajaxStart" );
242
243                 // Matches an absolute URL, and saves the domain
244                 var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url );
245
246                 // If we're requesting a remote document
247                 // and trying to load JSON or Script with a GET
248                 if ( s.dataType == "script" && type == "GET" && parts
249                         && ( parts[1] && parts[1] != location.protocol || parts[2] != location.host )){
250
251                         var head = document.getElementsByTagName("head")[0];
252                         var script = document.createElement("script");
253                         script.src = s.url;
254                         if (s.scriptCharset)
255                                 script.charset = s.scriptCharset;
256
257                         // Handle Script loading
258                         if ( !jsonp ) {
259                                 var done = false;
260
261                                 // Attach handlers for all browsers
262                                 script.onload = script.onreadystatechange = function(){
263                                         if ( !done && (!this.readyState ||
264                                                         this.readyState == "loaded" || this.readyState == "complete") ) {
265                                                 done = true;
266                                                 success();
267                                                 complete();
268                                                 head.removeChild( script );
269                                         }
270                                 };
271                         }
272
273                         head.appendChild(script);
274
275                         // We handle everything using the script element injection
276                         return undefined;
277                 }
278
279                 var requestDone = false;
280
281                 // Create the request object
282                 var xhr = s.xhr();
283
284                 // Open the socket
285                 // Passing null username, generates a login popup on Opera (#2865)
286                 if( s.username )
287                         xhr.open(type, s.url, s.async, s.username, s.password);
288                 else
289                         xhr.open(type, s.url, s.async);
290
291                 // Need an extra try/catch for cross domain requests in Firefox 3
292                 try {
293                         // Set the correct header, if data is being sent
294                         if ( s.data )
295                                 xhr.setRequestHeader("Content-Type", s.contentType);
296
297                         // Set the If-Modified-Since header, if ifModified mode.
298                         if ( s.ifModified )
299                                 xhr.setRequestHeader("If-Modified-Since",
300                                         jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
301
302                         // Set header so the called script knows that it's an XMLHttpRequest
303                         xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
304
305                         // Set the Accepts header for the server, depending on the dataType
306                         xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
307                                 s.accepts[ s.dataType ] + ", */*" :
308                                 s.accepts._default );
309                 } catch(e){}
310
311                 // Allow custom headers/mimetypes and early abort
312                 if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
313                         // Handle the global AJAX counter
314                         if ( s.global && ! --jQuery.active )
315                                 jQuery.event.trigger( "ajaxStop" );
316                         // close opended socket
317                         xhr.abort();
318                         return false;
319                 }
320
321                 if ( s.global )
322                         jQuery.event.trigger("ajaxSend", [xhr, s]);
323
324                 // Wait for a response to come back
325                 var onreadystatechange = function(isTimeout){
326                         // The request was aborted, clear the interval and decrement jQuery.active
327                         if (xhr.readyState == 0) {
328                                 if (ival) {
329                                         // clear poll interval
330                                         clearInterval(ival);
331                                         ival = null;
332                                         // Handle the global AJAX counter
333                                         if ( s.global && ! --jQuery.active )
334                                                 jQuery.event.trigger( "ajaxStop" );
335                                 }
336                         // The transfer is complete and the data is available, or the request timed out
337                         } else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
338                                 requestDone = true;
339
340                                 // clear poll interval
341                                 if (ival) {
342                                         clearInterval(ival);
343                                         ival = null;
344                                 }
345
346                                 status = isTimeout == "timeout" ? "timeout" :
347                                         !jQuery.httpSuccess( xhr ) ? "error" :
348                                         s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" :
349                                         "success";
350
351                                 if ( status == "success" ) {
352                                         // Watch for, and catch, XML document parse errors
353                                         try {
354                                                 // process the data (runs the xml through httpData regardless of callback)
355                                                 data = jQuery.httpData( xhr, s.dataType, s );
356                                         } catch(e) {
357                                                 status = "parsererror";
358                                         }
359                                 }
360
361                                 // Make sure that the request was successful or notmodified
362                                 if ( status == "success" ) {
363                                         // Cache Last-Modified header, if ifModified mode.
364                                         var modRes;
365                                         try {
366                                                 modRes = xhr.getResponseHeader("Last-Modified");
367                                         } catch(e) {} // swallow exception thrown by FF if header is not available
368
369                                         if ( s.ifModified && modRes )
370                                                 jQuery.lastModified[s.url] = modRes;
371
372                                         // JSONP handles its own success callback
373                                         if ( !jsonp )
374                                                 success();
375                                 } else
376                                         jQuery.handleError(s, xhr, status);
377
378                                 // Fire the complete handlers
379                                 complete();
380
381                                 // Stop memory leaks
382                                 if ( s.async )
383                                         xhr = null;
384                         }
385                 };
386
387                 if ( s.async ) {
388                         // don't attach the handler to the request, just poll it instead
389                         var ival = setInterval(onreadystatechange, 13);
390
391                         // Timeout checker
392                         if ( s.timeout > 0 )
393                                 setTimeout(function(){
394                                         // Check to see if the request is still happening
395                                         if ( xhr ) {
396                                                 if( !requestDone )
397                                                         onreadystatechange( "timeout" );
398
399                                                 // Cancel the request
400                                                 if ( xhr )
401                                                         xhr.abort();
402                                         }
403                                 }, s.timeout);
404                 }
405
406                 // Send the data
407                 try {
408                         xhr.send(s.data);
409                 } catch(e) {
410                         jQuery.handleError(s, xhr, null, e);
411                 }
412
413                 // firefox 1.5 doesn't fire statechange for sync requests
414                 if ( !s.async )
415                         onreadystatechange();
416
417                 function success(){
418                         // If a local callback was specified, fire it and pass it the data
419                         if ( s.success )
420                                 s.success( data, status );
421
422                         // Fire the global callback
423                         if ( s.global )
424                                 jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
425                 }
426
427                 function complete(){
428                         // Process result
429                         if ( s.complete )
430                                 s.complete(xhr, status);
431
432                         // The request was completed
433                         if ( s.global )
434                                 jQuery.event.trigger( "ajaxComplete", [xhr, s] );
435
436                         // Handle the global AJAX counter
437                         if ( s.global && ! --jQuery.active )
438                                 jQuery.event.trigger( "ajaxStop" );
439                 }
440
441                 // return XMLHttpRequest to allow aborting the request etc.
442                 return xhr;
443         },
444
445         handleError: function( s, xhr, status, e ) {
446                 // If a local callback was specified, fire it
447                 if ( s.error ) s.error( xhr, status, e );
448
449                 // Fire the global callback
450                 if ( s.global )
451                         jQuery.event.trigger( "ajaxError", [xhr, s, e] );
452         },
453
454         // Counter for holding the number of active queries
455         active: 0,
456
457         // Determines if an XMLHttpRequest was successful or not
458         httpSuccess: function( xhr ) {
459                 try {
460                         // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
461                         return !xhr.status && location.protocol == "file:" ||
462                                 ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;
463                 } catch(e){}
464                 return false;
465         },
466
467         // Determines if an XMLHttpRequest returns NotModified
468         httpNotModified: function( xhr, url ) {
469                 try {
470                         var xhrRes = xhr.getResponseHeader("Last-Modified");
471
472                         // Firefox always returns 200. check Last-Modified date
473                         return xhr.status == 304 || xhrRes == jQuery.lastModified[url];
474                 } catch(e){}
475                 return false;
476         },
477
478         httpData: function( xhr, type, s ) {
479                 var ct = xhr.getResponseHeader("content-type"),
480                         xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
481                         data = xml ? xhr.responseXML : xhr.responseText;
482
483                 if ( xml && data.documentElement.tagName == "parsererror" )
484                         throw "parsererror";
485                         
486                 // Allow a pre-filtering function to sanitize the response
487                 // s != null is checked to keep backwards compatibility
488                 if( s && s.dataFilter )
489                         data = s.dataFilter( data, type );
490
491                 // The filter can actually parse the response
492                 if( typeof data === "string" ){
493
494                         // If the type is "script", eval it in global context
495                         if ( type == "script" )
496                                 jQuery.globalEval( data );
497
498                         // Get the JavaScript object, if JSON is used.
499                         if ( type == "json" )
500                                 data = window["eval"]("(" + data + ")");
501                 }
502                 
503                 return data;
504         },
505
506         // Serialize an array of form elements or a set of
507         // key/values into a query string
508         param: function( a ) {
509                 var s = [ ];
510
511                 function add( key, value ){
512                         s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
513                 };
514
515                 // If an array was passed in, assume that it is an array
516                 // of form elements
517                 if ( jQuery.isArray(a) || a.jquery )
518                         // Serialize the form elements
519                         jQuery.each( a, function(){
520                                 add( this.name, this.value );
521                         });
522
523                 // Otherwise, assume that it's an object of key/value pairs
524                 else
525                         // Serialize the key/values
526                         for ( var j in a )
527                                 // If the value is an array then the key names need to be repeated
528                                 if ( jQuery.isArray(a[j]) )
529                                         jQuery.each( a[j], function(){
530                                                 add( j, this );
531                                         });
532                                 else
533                                         add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );
534
535                 // Return the resulting serialization
536                 return s.join("&").replace(/%20/g, "+");
537         }
538
539 });