Did some cleaning up of ajax.js and fixed a bug from commit [6457].
[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|search/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                 contentType: "application/x-www-form-urlencoded",
147                 processData: true,
148                 async: true,
149                 /*
150                 timeout: 0,
151                 data: null,
152                 username: null,
153                 password: null,
154                 */
155                 // Create the request object; Microsoft failed to properly
156                 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
157                 // This function can be overriden by calling jQuery.ajaxSetup
158                 xhr:function(){
159                         return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
160                 },
161                 accepts: {
162                         xml: "application/xml, text/xml",
163                         html: "text/html",
164                         script: "text/javascript, application/javascript",
165                         json: "application/json, text/javascript",
166                         text: "text/plain",
167                         _default: "*/*"
168                 }
169         },
170
171         // Last-Modified header cache for next request
172         lastModified: {},
173         etag: {},
174
175         ajax: function( s ) {
176                 // Extend the settings, but re-extend 's' so that it can be
177                 // checked again later (in the test suite, specifically)
178                 s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
179
180                 var jsonp, jsre = /=\?(&|$)/, status, data,
181                         type = s.type.toUpperCase();
182
183                 // convert data if not already a string
184                 if ( s.data && s.processData && typeof s.data !== "string" ) {
185                         s.data = jQuery.param(s.data);
186                 }
187
188                 // Handle JSONP Parameter Callbacks
189                 if ( s.dataType == "jsonp" ) {
190                         if ( type == "GET" ) {
191                                 if ( !jsre.test( s.url ) ) {
192                                         s.url += (/\?/.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
193                                 }
194                         } else if ( !s.data || !jsre.test(s.data) ) {
195                                 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
196                         }
197                         s.dataType = "json";
198                 }
199
200                 // Build temporary JSONP function
201                 if ( s.dataType == "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
202                         jsonp = "jsonp" + jsc++;
203
204                         // Replace the =? sequence both in the query string and the data
205                         if ( s.data ) {
206                                 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
207                         }
208
209                         s.url = s.url.replace(jsre, "=" + jsonp + "$1");
210
211                         // We need to make sure
212                         // that a JSONP style response is executed properly
213                         s.dataType = "script";
214
215                         // Handle JSONP-style loading
216                         window[ jsonp ] = function(tmp){
217                                 data = tmp;
218                                 success();
219                                 complete();
220                                 // Garbage collect
221                                 window[ jsonp ] = undefined;
222                                 try{ delete window[ jsonp ]; } catch(e){}
223                                 if ( head )
224                                         head.removeChild( script );
225                         };
226                 }
227
228                 if ( s.dataType == "script" && s.cache == null )
229                         s.cache = false;
230
231                 if ( s.cache === false && type == "GET" ) {
232                         var ts = now();
233                         // try replacing _= if it is there
234                         var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
235                         // if nothing was replaced, add timestamp to the end
236                         s.url = ret + ((ret == s.url) ? (/\?/.test(s.url) ? "&" : "?") + "_=" + ts : "");
237                 }
238
239                 // If data is available, append data to url for get requests
240                 if ( s.data && type == "GET" ) {
241                         s.url += (/\?/.test(s.url) ? "&" : "?") + s.data;
242                 }
243
244                 // Watch for a new set of requests
245                 if ( s.global && ! jQuery.active++ )
246                         jQuery.event.trigger( "ajaxStart" );
247
248                 // Matches an absolute URL, and saves the domain
249                 var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url );
250
251                 // If we're requesting a remote document
252                 // and trying to load JSON or Script with a GET
253                 if ( s.dataType == "script" && type == "GET" && parts
254                         && ( parts[1] && parts[1] != location.protocol || parts[2] != location.host )){
255
256                         var head = document.getElementsByTagName("head")[0];
257                         var script = document.createElement("script");
258                         script.src = s.url;
259                         if (s.scriptCharset)
260                                 script.charset = s.scriptCharset;
261
262                         // Handle Script loading
263                         if ( !jsonp ) {
264                                 var done = false;
265
266                                 // Attach handlers for all browsers
267                                 script.onload = script.onreadystatechange = function(){
268                                         if ( !done && (!this.readyState ||
269                                                         this.readyState == "loaded" || this.readyState == "complete") ) {
270                                                 done = true;
271                                                 success();
272                                                 complete();
273
274                                                 // Handle memory leak in IE
275                                                 script.onload = script.onreadystatechange = null;
276                                                 head.removeChild( script );
277                                         }
278                                 };
279                         }
280
281                         // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
282                         // This arises when a base node is used (#2709 and #4378).
283                         head.insertBefore( script, head.firstChild );
284
285                         // We handle everything using the script element injection
286                         return undefined;
287                 }
288
289                 var requestDone = false;
290
291                 // Create the request object
292                 var xhr = s.xhr();
293
294                 // Open the socket
295                 // Passing null username, generates a login popup on Opera (#2865)
296                 if( s.username )
297                         xhr.open(type, s.url, s.async, s.username, s.password);
298                 else
299                         xhr.open(type, s.url, s.async);
300
301                 // Need an extra try/catch for cross domain requests in Firefox 3
302                 try {
303                         // Set the correct header, if data is being sent
304                         if ( s.data )
305                                 xhr.setRequestHeader("Content-Type", s.contentType);
306
307                                 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
308                                 if ( s.ifModified ) {
309                                         if (jQuery.lastModified[s.url])
310                                                 xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
311                                         if (jQuery.etag[s.url])
312                                                 xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
313                                 }
314
315                         // Set header so the called script knows that it's an XMLHttpRequest
316                         xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
317
318                         // Set the Accepts header for the server, depending on the dataType
319                         xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
320                                 s.accepts[ s.dataType ] + ", */*" :
321                                 s.accepts._default );
322                 } catch(e){}
323
324                 // Allow custom headers/mimetypes and early abort
325                 if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
326                         // Handle the global AJAX counter
327                         if ( s.global && ! --jQuery.active )
328                                 jQuery.event.trigger( "ajaxStop" );
329                         // close opended socket
330                         xhr.abort();
331                         return false;
332                 }
333
334                 if ( s.global )
335                         jQuery.event.trigger("ajaxSend", [xhr, s]);
336
337                 // Wait for a response to come back
338                 var onreadystatechange = function(isTimeout){
339                         // The request was aborted, clear the interval and decrement jQuery.active
340                         if (xhr.readyState == 0) {
341                                 if (ival) {
342                                         // clear poll interval
343                                         clearInterval(ival);
344                                         ival = null;
345                                         // Handle the global AJAX counter
346                                         if ( s.global && ! --jQuery.active )
347                                                 jQuery.event.trigger( "ajaxStop" );
348                                 }
349                         // The transfer is complete and the data is available, or the request timed out
350                         } else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
351                                 requestDone = true;
352
353                                 // clear poll interval
354                                 if (ival) {
355                                         clearInterval(ival);
356                                         ival = null;
357                                 }
358
359                                 status = isTimeout == "timeout" ? "timeout" :
360                                         !jQuery.httpSuccess( xhr ) ? "error" :
361                                         s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" :
362                                         "success";
363
364                                 if ( status == "success" ) {
365                                         // Watch for, and catch, XML document parse errors
366                                         try {
367                                                 // process the data (runs the xml through httpData regardless of callback)
368                                                 data = jQuery.httpData( xhr, s.dataType, s );
369                                         } catch(e) {
370                                                 status = "parsererror";
371                                         }
372                                 }
373
374                                 // Make sure that the request was successful or notmodified
375                                 if ( status == "success" || status == "notmodified" ) {
376                                         // JSONP handles its own success callback
377                                         if ( !jsonp )
378                                                 success();
379                                 } else
380                                         jQuery.handleError(s, xhr, status);
381
382                                 // Fire the complete handlers
383                                 complete();
384
385                                 if ( isTimeout )
386                                         xhr.abort();
387
388                                 // Stop memory leaks
389                                 if ( s.async )
390                                         xhr = null;
391                         }
392                 };
393
394                 if ( s.async ) {
395                         // don't attach the handler to the request, just poll it instead
396                         var ival = setInterval(onreadystatechange, 13);
397
398                         // Timeout checker
399                         if ( s.timeout > 0 )
400                                 setTimeout(function(){
401                                         // Check to see if the request is still happening
402                                         if ( xhr && !requestDone )
403                                                 onreadystatechange( "timeout" );
404                                 }, s.timeout);
405                 }
406
407                 // Send the data
408                 try {
409                         xhr.send( type === "POST" ? s.data : null );
410                 } catch(e) {
411                         jQuery.handleError(s, xhr, null, e);
412                 }
413
414                 // firefox 1.5 doesn't fire statechange for sync requests
415                 if ( !s.async )
416                         onreadystatechange();
417
418                 function success(){
419                         // If a local callback was specified, fire it and pass it the data
420                         if ( s.success )
421                                 s.success( data, status );
422
423                         // Fire the global callback
424                         if ( s.global )
425                                 jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
426                 }
427
428                 function complete(){
429                         // Process result
430                         if ( s.complete )
431                                 s.complete(xhr, status);
432
433                         // The request was completed
434                         if ( s.global )
435                                 jQuery.event.trigger( "ajaxComplete", [xhr, s] );
436
437                         // Handle the global AJAX counter
438                         if ( s.global && ! --jQuery.active )
439                                 jQuery.event.trigger( "ajaxStop" );
440                 }
441
442                 // return XMLHttpRequest to allow aborting the request etc.
443                 return xhr;
444         },
445
446         handleError: function( s, xhr, status, e ) {
447                 // If a local callback was specified, fire it
448                 if ( s.error ) s.error( xhr, status, e );
449
450                 // Fire the global callback
451                 if ( s.global )
452                         jQuery.event.trigger( "ajaxError", [xhr, s, e] );
453         },
454
455         // Counter for holding the number of active queries
456         active: 0,
457
458         // Determines if an XMLHttpRequest was successful or not
459         httpSuccess: function( xhr ) {
460                 try {
461                         // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
462                         return !xhr.status && location.protocol == "file:" ||
463                                 // Opera returns 0 when status is 304
464                                 ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223 || xhr.status == 0;
465                 } catch(e){}
466                 return false;
467         },
468
469         // Determines if an XMLHttpRequest returns NotModified
470         httpNotModified: function( xhr, url ) {
471                 var last_modified = xhr.getResponseHeader("Last-Modified");
472                 var etag = xhr.getResponseHeader("Etag");
473
474                 if (last_modified) 
475                         jQuery.lastModified[url] = last_modified;
476
477                 if (etag) 
478                         jQuery.etag[url] = etag;
479
480                 // Opera returns 0 when status is 304
481                 return xhr.status == 304 || xhr.status == 0;
482         },
483
484         httpData: function( xhr, type, s ) {
485                 var ct = xhr.getResponseHeader("content-type"),
486                         xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
487                         data = xml ? xhr.responseXML : xhr.responseText;
488
489                 if ( xml && data.documentElement.nodeName == "parsererror" ) {
490                         throw "parsererror";
491                 }
492
493                 // Allow a pre-filtering function to sanitize the response
494                 // s != null is checked to keep backwards compatibility
495                 if ( s && s.dataFilter ) {
496                         data = s.dataFilter( data, type );
497                 }
498
499                 // The filter can actually parse the response
500                 if ( typeof data === "string" ) {
501
502                         // If the type is "script", eval it in global context
503                         if ( type === "script" ) {
504                                 jQuery.globalEval( data );
505                         }
506
507                         // Get the JavaScript object, if JSON is used.
508                         if ( type == "json" ) {
509                                 if ( typeof JSON === "object" && JSON.parse ) {
510                                         data = JSON.parse( data );
511                                 } else {
512                                         data = (new Function("return " + data))();
513                                 }
514                         }
515                 }
516
517                 return data;
518         },
519
520         // Serialize an array of form elements or a set of
521         // key/values into a query string
522         param: function( a ) {
523                 var s = [ ];
524
525                 function add( key, value ){
526                         s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
527                 };
528
529                 // If an array was passed in, assume that it is an array
530                 // of form elements
531                 if ( jQuery.isArray(a) || a.jquery )
532                         // Serialize the form elements
533                         jQuery.each( a, function(){
534                                 add( this.name, this.value );
535                         });
536
537                 // Otherwise, assume that it's an object of key/value pairs
538                 else
539                         // Serialize the key/values
540                         for ( var j in a )
541                                 // If the value is an array then the key names need to be repeated
542                                 if ( jQuery.isArray(a[j]) )
543                                         jQuery.each( a[j], function(){
544                                                 add( j, this );
545                                         });
546                                 else
547                                         add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );
548
549                 // Return the resulting serialization
550                 return s.join("&").replace(/%20/g, "+");
551         }
552
553 });