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