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