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