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