193a85ae04075dac0514fd126b1bd4290ff6d854
[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: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ?
182                         function() {
183                                 return new window.XMLHttpRequest();
184                         } :
185                         function() {
186                                 try {
187                                         return new window.ActiveXObject("Microsoft.XMLHTTP");
188                                 } catch(e) {}
189                         },
190                 accepts: {
191                         xml: "application/xml, text/xml",
192                         html: "text/html",
193                         script: "text/javascript, application/javascript",
194                         json: "application/json, text/javascript",
195                         text: "text/plain",
196                         _default: "*/*"
197                 }
198         },
199
200         // Last-Modified header cache for next request
201         lastModified: {},
202         etag: {},
203
204         ajax: function( origSettings ) {
205                 var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings);
206                 
207                 var jsonp, status, data,
208                         callbackContext = s.context || s,
209                         type = s.type.toUpperCase();
210
211                 // convert data if not already a string
212                 if ( s.data && s.processData && typeof s.data !== "string" ) {
213                         s.data = jQuery.param( s.data, s.traditional );
214                 }
215
216                 // Handle JSONP Parameter Callbacks
217                 if ( s.dataType === "jsonp" ) {
218                         if ( type === "GET" ) {
219                                 if ( !jsre.test( s.url ) ) {
220                                         s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
221                                 }
222                         } else if ( !s.data || !jsre.test(s.data) ) {
223                                 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
224                         }
225                         s.dataType = "json";
226                 }
227
228                 // Build temporary JSONP function
229                 if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
230                         jsonp = s.jsonpCallback || ("jsonp" + jsc++);
231
232                         // Replace the =? sequence both in the query string and the data
233                         if ( s.data ) {
234                                 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
235                         }
236
237                         s.url = s.url.replace(jsre, "=" + jsonp + "$1");
238
239                         // We need to make sure
240                         // that a JSONP style response is executed properly
241                         s.dataType = "script";
242
243                         // Handle JSONP-style loading
244                         window[ jsonp ] = window[ jsonp ] || function( tmp ) {
245                                 data = tmp;
246                                 success();
247                                 complete();
248                                 // Garbage collect
249                                 window[ jsonp ] = undefined;
250
251                                 try {
252                                         delete window[ jsonp ];
253                                 } catch(e) {}
254
255                                 if ( head ) {
256                                         head.removeChild( script );
257                                 }
258                         };
259                 }
260
261                 if ( s.dataType === "script" && s.cache === null ) {
262                         s.cache = false;
263                 }
264
265                 if ( s.cache === false && type === "GET" ) {
266                         var ts = now();
267
268                         // try replacing _= if it is there
269                         var ret = s.url.replace(rts, "$1_=" + ts + "$2");
270
271                         // if nothing was replaced, add timestamp to the end
272                         s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
273                 }
274
275                 // If data is available, append data to url for get requests
276                 if ( s.data && type === "GET" ) {
277                         s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
278                 }
279
280                 // Watch for a new set of requests
281                 if ( s.global && ! jQuery.active++ ) {
282                         jQuery.event.trigger( "ajaxStart" );
283                 }
284
285                 // Matches an absolute URL, and saves the domain
286                 var parts = rurl.exec( s.url ),
287                         remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
288
289                 // If we're requesting a remote document
290                 // and trying to load JSON or Script with a GET
291                 if ( s.dataType === "script" && type === "GET" && remote ) {
292                         var head = document.getElementsByTagName("head")[0] || document.documentElement;
293                         var script = document.createElement("script");
294                         script.src = s.url;
295                         if ( s.scriptCharset ) {
296                                 script.charset = s.scriptCharset;
297                         }
298
299                         // Handle Script loading
300                         if ( !jsonp ) {
301                                 var done = false;
302
303                                 // Attach handlers for all browsers
304                                 script.onload = script.onreadystatechange = function() {
305                                         if ( !done && (!this.readyState ||
306                                                         this.readyState === "loaded" || this.readyState === "complete") ) {
307                                                 done = true;
308                                                 success();
309                                                 complete();
310
311                                                 // Handle memory leak in IE
312                                                 script.onload = script.onreadystatechange = null;
313                                                 if ( head && script.parentNode ) {
314                                                         head.removeChild( script );
315                                                 }
316                                         }
317                                 };
318                         }
319
320                         // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
321                         // This arises when a base node is used (#2709 and #4378).
322                         head.insertBefore( script, head.firstChild );
323
324                         // We handle everything using the script element injection
325                         return undefined;
326                 }
327
328                 var requestDone = false;
329
330                 // Create the request object
331                 var xhr = s.xhr();
332
333                 if ( !xhr ) {
334                         return;
335                 }
336
337                 // Open the socket
338                 // Passing null username, generates a login popup on Opera (#2865)
339                 if ( s.username ) {
340                         xhr.open(type, s.url, s.async, s.username, s.password);
341                 } else {
342                         xhr.open(type, s.url, s.async);
343                 }
344
345                 // Need an extra try/catch for cross domain requests in Firefox 3
346                 try {
347                         // Set the correct header, if data is being sent
348                         if ( s.data || origSettings && origSettings.contentType ) {
349                                 xhr.setRequestHeader("Content-Type", s.contentType);
350                         }
351
352                         // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
353                         if ( s.ifModified ) {
354                                 if ( jQuery.lastModified[s.url] ) {
355                                         xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
356                                 }
357
358                                 if ( jQuery.etag[s.url] ) {
359                                         xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
360                                 }
361                         }
362
363                         // Set header so the called script knows that it's an XMLHttpRequest
364                         // Only send the header if it's not a remote XHR
365                         if ( !remote ) {
366                                 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
367                         }
368
369                         // Set the Accepts header for the server, depending on the dataType
370                         xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
371                                 s.accepts[ s.dataType ] + ", */*" :
372                                 s.accepts._default );
373                 } catch(e) {}
374
375                 // Allow custom headers/mimetypes and early abort
376                 if ( s.beforeSend && s.beforeSend.call(callbackContext, xhr, s) === false ) {
377                         // Handle the global AJAX counter
378                         if ( s.global && ! --jQuery.active ) {
379                                 jQuery.event.trigger( "ajaxStop" );
380                         }
381
382                         // close opended socket
383                         xhr.abort();
384                         return false;
385                 }
386
387                 if ( s.global ) {
388                         trigger("ajaxSend", [xhr, s]);
389                 }
390
391                 // Wait for a response to come back
392                 var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
393                         // The request was aborted, clear the interval and decrement jQuery.active
394                         if ( !xhr || xhr.readyState === 0 ) {
395                                 requestDone = true;
396                                 xhr.onreadystatechange = jQuery.noop;
397
398                                 // Handle the global AJAX counter
399                                 if ( s.global && ! --jQuery.active ) {
400                                         jQuery.event.trigger( "ajaxStop" );
401                                 }
402
403                         // The transfer is complete and the data is available, or the request timed out
404                         } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
405                                 requestDone = true;
406                                 xhr.onreadystatechange = jQuery.noop;
407
408                                 status = isTimeout === "timeout" ?
409                                         "timeout" :
410                                         !jQuery.httpSuccess( xhr ) ?
411                                                 "error" :
412                                                 s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
413                                                         "notmodified" :
414                                                         "success";
415
416                                 if ( status === "success" ) {
417                                         // Watch for, and catch, XML document parse errors
418                                         try {
419                                                 // process the data (runs the xml through httpData regardless of callback)
420                                                 data = jQuery.httpData( xhr, s.dataType, s );
421                                         } catch(e) {
422                                                 status = "parsererror";
423                                         }
424                                 }
425
426                                 // Make sure that the request was successful or notmodified
427                                 if ( status === "success" || status === "notmodified" ) {
428                                         // JSONP handles its own success callback
429                                         if ( !jsonp ) {
430                                                 success();
431                                         }
432                                 } else {
433                                         jQuery.handleError(s, xhr, status);
434                                 }
435
436                                 // Fire the complete handlers
437                                 complete();
438
439                                 if ( isTimeout === "timeout" ) {
440                                         xhr.abort();
441                                 }
442
443                                 // Stop memory leaks
444                                 if ( s.async ) {
445                                         xhr = null;
446                                 }
447                         }
448                 };
449
450                 // Timeout checker
451                 if ( s.async && s.timeout > 0 ) {
452                         setTimeout(function() {
453                                 // Check to see if the request is still happening
454                                 if ( xhr && !requestDone ) {
455                                         onreadystatechange( "timeout" );
456                                 }
457                         }, s.timeout);
458                 }
459
460                 // Send the data
461                 try {
462                         xhr.send( type === "POST" || type === "PUT" ? s.data : null );
463                 } catch(e) {
464                         jQuery.handleError(s, xhr, null, e);
465                         // Fire the complete handlers
466                         complete();
467                 }
468
469                 // firefox 1.5 doesn't fire statechange for sync requests
470                 if ( !s.async ) {
471                         onreadystatechange();
472                 }
473
474                 function success() {
475                         // If a local callback was specified, fire it and pass it the data
476                         if ( s.success ) {
477                                 s.success.call( callbackContext, data, status, xhr );
478                         }
479
480                         // Fire the global callback
481                         if ( s.global ) {
482                                 trigger( "ajaxSuccess", [xhr, s] );
483                         }
484                 }
485
486                 function complete() {
487                         // Process result
488                         if ( s.complete ) {
489                                 s.complete.call( callbackContext, xhr, status);
490                         }
491
492                         // The request was completed
493                         if ( s.global ) {
494                                 trigger( "ajaxComplete", [xhr, s] );
495                         }
496
497                         // Handle the global AJAX counter
498                         if ( s.global && ! --jQuery.active ) {
499                                 jQuery.event.trigger( "ajaxStop" );
500                         }
501                 }
502                 
503                 function trigger(type, args) {
504                         (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args);
505                 }
506
507                 // return XMLHttpRequest to allow aborting the request etc.
508                 return xhr;
509         },
510
511         handleError: function( s, xhr, status, e ) {
512                 // If a local callback was specified, fire it
513                 if ( s.error ) {
514                         s.error.call( s.context || window, xhr, status, e );
515                 }
516
517                 // Fire the global callback
518                 if ( s.global ) {
519                         (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
520                 }
521         },
522
523         // Counter for holding the number of active queries
524         active: 0,
525
526         // Determines if an XMLHttpRequest was successful or not
527         httpSuccess: function( xhr ) {
528                 try {
529                         // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
530                         return !xhr.status && location.protocol === "file:" ||
531                                 // Opera returns 0 when status is 304
532                                 ( xhr.status >= 200 && xhr.status < 300 ) ||
533                                 xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
534                 } catch(e) {}
535
536                 return false;
537         },
538
539         // Determines if an XMLHttpRequest returns NotModified
540         httpNotModified: function( xhr, url ) {
541                 var lastModified = xhr.getResponseHeader("Last-Modified"),
542                         etag = xhr.getResponseHeader("Etag");
543
544                 if ( lastModified ) {
545                         jQuery.lastModified[url] = lastModified;
546                 }
547
548                 if ( etag ) {
549                         jQuery.etag[url] = etag;
550                 }
551
552                 // Opera returns 0 when status is 304
553                 return xhr.status === 304 || xhr.status === 0;
554         },
555
556         httpData: function( xhr, type, s ) {
557                 var ct = xhr.getResponseHeader("content-type") || "",
558                         xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
559                         data = xml ? xhr.responseXML : xhr.responseText;
560
561                 if ( xml && data.documentElement.nodeName === "parsererror" ) {
562                         throw "parsererror";
563                 }
564
565                 // Allow a pre-filtering function to sanitize the response
566                 // s is checked to keep backwards compatibility
567                 if ( s && s.dataFilter ) {
568                         data = s.dataFilter( data, type );
569                 }
570
571                 // The filter can actually parse the response
572                 if ( typeof data === "string" ) {
573                         // Get the JavaScript object, if JSON is used.
574                         if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
575                                 // Make sure the incoming data is actual JSON
576                                 // Logic borrowed from http://json.org/json2.js
577                                 if (/^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
578                                         .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
579                                         .replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) {
580
581                                         // Try to use the native JSON parser first
582                                         if ( window.JSON && window.JSON.parse ) {
583                                                 data = window.JSON.parse( data );
584
585                                         } else {
586                                                 data = (new Function("return " + data))();
587                                         }
588
589                                 } else {
590                                         throw "Invalid JSON: " + data;
591                                 }
592
593                         // If the type is "script", eval it in global context
594                         } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
595                                 jQuery.globalEval( data );
596                         }
597                 }
598
599                 return data;
600         },
601
602         // Serialize an array of form elements or a set of
603         // key/values into a query string
604         param: function( a, traditional ) {
605                 
606                 var s = [];
607                 
608                 // Set traditional to true for jQuery <= 1.3.2 behavior.
609                 if ( traditional === undefined ) {
610                         traditional = jQuery.ajaxSettings.traditional;
611                 }
612                 
613                 function add( key, value ) {
614                         // If value is a function, invoke it and return its value
615                         value = jQuery.isFunction(value) ? value() : value;
616                         s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
617                 }
618                 
619                 // If an array was passed in, assume that it is an array of form elements.
620                 if ( jQuery.isArray(a) || a.jquery ) {
621                         // Serialize the form elements
622                         jQuery.each( a, function() {
623                                 add( this.name, this.value );
624                         });
625                         
626                 } else {
627                         // If traditional, encode the "old" way (the way 1.3.2 or older
628                         // did it), otherwise encode params recursively.
629                         jQuery.each( a, function buildParams( prefix, obj ) {
630                                 
631                                 if ( jQuery.isArray(obj) ) {
632                                         // Serialize array item.
633                                         jQuery.each( obj, function( i, v ) {
634                                                 if ( traditional ) {
635                                                         // Treat each array item as a scalar.
636                                                         add( prefix, v );
637                                                 } else {
638                                                         // If array item is non-scalar (array or object), encode its
639                                                         // numeric index to resolve deserialization ambiguity issues.
640                                                         // Note that rack (as of 1.0.0) can't currently deserialize
641                                                         // nested arrays properly, and attempting to do so may cause
642                                                         // a server error. Possible fixes are to modify rack's
643                                                         // deserialization algorithm or to provide an option or flag
644                                                         // to force array serialization to be shallow.
645                                                         buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v );
646                                                 }
647                                         });
648                                         
649                                 } else if ( !traditional && typeof obj === "object" ) {
650                                         // Serialize object item.
651                                         jQuery.each( obj, function( k, v ) {
652                                                 buildParams( prefix + "[" + k + "]", v );
653                                         });
654                                         
655                                 } else {
656                                         // Serialize scalar item.
657                                         add( prefix, obj );
658                                 }
659                         });
660                 }
661                 
662                 // Return the resulting serialization
663                 return s.join("&").replace(r20, "+");
664         }
665
666 });