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