More changes to get jQuery in line with JSLint.
[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         // Keep a copy of the old load method
12         _load = jQuery.fn.load;
13
14 jQuery.fn.extend({
15         load: function( url, params, callback ) {
16                 if ( typeof url !== "string" && _load ) {
17                         return _load.apply( this, arguments );
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                 var self = this;
49
50                 // Request the remote document
51                 jQuery.ajax({
52                         url: url,
53                         type: type,
54                         dataType: "html",
55                         data: params,
56                         complete: function( res, status ) {
57                                 // If successful, inject the HTML into all the matched elements
58                                 if ( status === "success" || status === "notmodified" ) {
59                                         // See if a selector was specified
60                                         self.html( selector ?
61                                                 // Create a dummy div to hold the results
62                                                 jQuery("<div />")
63                                                         // inject the contents of the document in, removing the scripts
64                                                         // to avoid any 'Permission Denied' errors in IE
65                                                         .append(res.responseText.replace(rscript, ""))
66
67                                                         // Locate the specified elements
68                                                         .find(selector) :
69
70                                                 // If not, just inject the full result
71                                                 res.responseText );
72                                 }
73
74                                 if ( callback ) {
75                                         self.each( callback, [res.responseText, status, res] );
76                                 }
77                         }
78                 });
79
80                 return this;
81         },
82
83         serialize: function() {
84                 return jQuery.param(this.serializeArray());
85         },
86         serializeArray: function() {
87                 return this.map(function() {
88                         return this.elements ? jQuery.makeArray(this.elements) : this;
89                 })
90                 .filter(function() {
91                         return this.name && !this.disabled &&
92                                 (this.checked || rselectTextarea.test(this.nodeName) ||
93                                         rinput.test(this.type));
94                 })
95                 .map(function( i, elem ) {
96                         var val = jQuery(this).val();
97
98                         return val == null ?
99                                 null :
100                                 jQuery.isArray(val) ?
101                                         jQuery.map( val, function( val, i ) {
102                                                 return { name: elem.name, value: val };
103                                         }) :
104                                         { name: elem.name, value: val };
105                 }).get();
106         }
107 });
108
109 // Attach a bunch of functions for handling common AJAX events
110 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) {
111         jQuery.fn[o] = function( f ) {
112                 return this.bind(o, f);
113         };
114 });
115
116 jQuery.extend({
117
118         get: function( url, data, callback, type ) {
119                 // shift arguments if data argument was omited
120                 if ( jQuery.isFunction( data ) ) {
121                         type = type || callback;
122                         callback = data;
123                         data = null;
124                 }
125
126                 return jQuery.ajax({
127                         type: "GET",
128                         url: url,
129                         data: data,
130                         success: callback,
131                         dataType: type
132                 });
133         },
134
135         getScript: function( url, callback ) {
136                 return jQuery.get(url, null, callback, "script");
137         },
138
139         getJSON: function( url, data, callback ) {
140                 return jQuery.get(url, data, callback, "json");
141         },
142
143         post: function( url, data, callback, type ) {
144                 // shift arguments if data argument was omited
145                 if ( jQuery.isFunction( data ) ) {
146                         type = type || callback;
147                         callback = data;
148                         data = {};
149                 }
150
151                 return jQuery.ajax({
152                         type: "POST",
153                         url: url,
154                         data: data,
155                         success: callback,
156                         dataType: type
157                 });
158         },
159
160         ajaxSetup: function( settings ) {
161                 jQuery.extend( jQuery.ajaxSettings, settings );
162         },
163
164         ajaxSettings: {
165                 url: location.href,
166                 global: true,
167                 type: "GET",
168                 contentType: "application/x-www-form-urlencoded",
169                 processData: true,
170                 async: true,
171                 /*
172                 timeout: 0,
173                 data: null,
174                 username: null,
175                 password: null,
176                 traditional: false,
177                 */
178                 // Create the request object; Microsoft failed to properly
179                 // implement the XMLHttpRequest in IE7 (can't request local files),
180                 // so we use the ActiveXObject when it is available
181                 // This function can be overriden by calling jQuery.ajaxSetup
182                 xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ?
183                         function() {
184                                 return new window.XMLHttpRequest();
185                         } :
186                         function() {
187                                 try {
188                                         return new window.ActiveXObject("Microsoft.XMLHTTP");
189                                 } catch(e) {}
190                         },
191                 accepts: {
192                         xml: "application/xml, text/xml",
193                         html: "text/html",
194                         script: "text/javascript, application/javascript",
195                         json: "application/json, text/javascript",
196                         text: "text/plain",
197                         _default: "*/*"
198                 }
199         },
200
201         // Last-Modified header cache for next request
202         lastModified: {},
203         etag: {},
204
205         ajax: function( origSettings ) {
206                 var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
207                         jsonp, status, data, type = s.type.toUpperCase();
208
209                 s.context = origSettings && origSettings.context || s;
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                                 jQuery.ajax.handleSuccess( s, xhr, status, data );
247                                 jQuery.ajax.handleComplete( s, xhr, status, data );
248                                 // Garbage collect
249                                 window[ jsonp ] = undefined;
250
251                                 try {
252                                         delete window[ jsonp ];
253                                 } catch( jsonpError ) {}
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.ajax.active++ === 0 ) {
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                                                 jQuery.ajax.handleSuccess( s, xhr, status, data );
309                                                 jQuery.ajax.handleComplete( s, xhr, status, data );
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( headerError ) {}
374
375                 // Allow custom headers/mimetypes and early abort
376                 if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) {
377                         // Handle the global AJAX counter
378                         if ( s.global && jQuery.ajax.active-- === 1 ) {
379                                 jQuery.event.trigger( "ajaxStop" );
380                         }
381
382                         // close opended socket
383                         xhr.abort();
384                         return false;
385                 }
386
387                 if ( s.global ) {
388                         jQuery.ajax.triggerGlobal( s, "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
394                         if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
395                                 // Opera doesn't call onreadystatechange before this point
396                                 // so we simulate the call
397                                 if ( !requestDone ) {
398                                         jQuery.ajax.handleComplete( s, xhr, status, data );
399                                 }
400
401                                 requestDone = true;
402                                 if ( xhr ) {
403                                         xhr.onreadystatechange = jQuery.noop;
404                                 }
405
406                         // The transfer is complete and the data is available, or the request timed out
407                         } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
408                                 requestDone = true;
409                                 xhr.onreadystatechange = jQuery.noop;
410
411                                 status = isTimeout === "timeout" ?
412                                         "timeout" :
413                                         !jQuery.ajax.httpSuccess( xhr ) ?
414                                                 "error" :
415                                                 s.ifModified && jQuery.ajax.httpNotModified( xhr, s.url ) ?
416                                                         "notmodified" :
417                                                         "success";
418
419                                 var errMsg;
420
421                                 if ( status === "success" ) {
422                                         // Watch for, and catch, XML document parse errors
423                                         try {
424                                                 // process the data (runs the xml through httpData regardless of callback)
425                                                 data = jQuery.ajax.httpData( xhr, s.dataType, s );
426                                         } catch( parserError ) {
427                                                 status = "parsererror";
428                                                 errMsg = parserError;
429                                         }
430                                 }
431
432                                 // Make sure that the request was successful or notmodified
433                                 if ( status === "success" || status === "notmodified" ) {
434                                         // JSONP handles its own success callback
435                                         if ( !jsonp ) {
436                                                 jQuery.ajax.handleSuccess( s, xhr, status, data );
437                                         }
438                                 } else {
439                                         jQuery.ajax.handleError( s, xhr, status, errMsg );
440                                 }
441
442                                 // Fire the complete handlers
443                                 jQuery.ajax.handleComplete( s, xhr, status, data );
444
445                                 if ( isTimeout === "timeout" ) {
446                                         xhr.abort();
447                                 }
448
449                                 // Stop memory leaks
450                                 if ( s.async ) {
451                                         xhr = null;
452                                 }
453                         }
454                 };
455
456                 // Override the abort handler, if we can (IE doesn't allow it, but that's OK)
457                 // Opera doesn't fire onreadystatechange at all on abort
458                 try {
459                         var oldAbort = xhr.abort;
460                         xhr.abort = function() {
461                                 if ( xhr ) {
462                                         oldAbort.call( xhr );
463                                 }
464
465                                 onreadystatechange( "abort" );
466                         };
467                 } catch( abortError ) {}
468
469                 // Timeout checker
470                 if ( s.async && s.timeout > 0 ) {
471                         setTimeout(function() {
472                                 // Check to see if the request is still happening
473                                 if ( xhr && !requestDone ) {
474                                         onreadystatechange( "timeout" );
475                                 }
476                         }, s.timeout);
477                 }
478
479                 // Send the data
480                 try {
481                         xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null );
482
483                 } catch( sendError ) {
484                         jQuery.ajax.handleError( s, xhr, null, e );
485
486                         // Fire the complete handlers
487                         jQuery.ajax.handleComplete( s, xhr, status, data );
488                 }
489
490                 // firefox 1.5 doesn't fire statechange for sync requests
491                 if ( !s.async ) {
492                         onreadystatechange();
493                 }
494
495                 // return XMLHttpRequest to allow aborting the request etc.
496                 return xhr;
497         },
498
499         // Serialize an array of form elements or a set of
500         // key/values into a query string
501         param: function( a, traditional ) {
502                 var s = [], add = function( key, value ) {
503                         // If value is a function, invoke it and return its value
504                         value = jQuery.isFunction(value) ? value() : value;
505                         s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
506                 };
507                 
508                 // Set traditional to true for jQuery <= 1.3.2 behavior.
509                 if ( traditional === undefined ) {
510                         traditional = jQuery.ajaxSettings.traditional;
511                 }
512                 
513                 // If an array was passed in, assume that it is an array of form elements.
514                 if ( jQuery.isArray(a) || a.jquery ) {
515                         // Serialize the form elements
516                         jQuery.each( a, function() {
517                                 add( this.name, this.value );
518                         });
519                         
520                 } else {
521                         // If traditional, encode the "old" way (the way 1.3.2 or older
522                         // did it), otherwise encode params recursively.
523                         for ( var prefix in a ) {
524                                 buildParams( prefix, a[prefix], traditional, add );
525                         }
526                 }
527
528                 // Return the resulting serialization
529                 return s.join("&").replace(r20, "+");
530         }
531 });
532
533 function buildParams( prefix, obj, traditional, add ) {
534         if ( jQuery.isArray(obj) ) {
535                 // Serialize array item.
536                 jQuery.each( obj, function( i, v ) {
537                         if ( traditional || /\[\]$/.test( prefix ) ) {
538                                 // Treat each array item as a scalar.
539                                 add( prefix, v );
540
541                         } else {
542                                 // If array item is non-scalar (array or object), encode its
543                                 // numeric index to resolve deserialization ambiguity issues.
544                                 // Note that rack (as of 1.0.0) can't currently deserialize
545                                 // nested arrays properly, and attempting to do so may cause
546                                 // a server error. Possible fixes are to modify rack's
547                                 // deserialization algorithm or to provide an option or flag
548                                 // to force array serialization to be shallow.
549                                 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
550                         }
551                 });
552                         
553         } else if ( !traditional && obj != null && typeof obj === "object" ) {
554                 // Serialize object item.
555                 jQuery.each( obj, function( k, v ) {
556                         buildParams( prefix + "[" + k + "]", v, traditional, add );
557                 });
558                                         
559         } else {
560                 // Serialize scalar item.
561                 add( prefix, obj );
562         }
563 }
564
565 jQuery.extend( jQuery.ajax, {
566
567         // Counter for holding the number of active queries
568         active: 0,
569
570         handleError: function( s, xhr, status, e ) {
571                 // If a local callback was specified, fire it
572                 if ( s.error ) {
573                         s.error.call( s.context, xhr, status, e );
574                 }
575
576                 // Fire the global callback
577                 if ( s.global ) {
578                         jQuery.ajax.triggerGlobal( s, "ajaxError", [xhr, s, e] );
579                 }
580         },
581
582         handleSuccess: function( s, xhr, status, data ) {
583                 // If a local callback was specified, fire it and pass it the data
584                 if ( s.success ) {
585                         s.success.call( s.context, data, status, xhr );
586                 }
587
588                 // Fire the global callback
589                 if ( s.global ) {
590                         jQuery.ajax.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
591                 }
592         },
593
594         handleComplete: function( s, xhr, status ) {
595                 // Process result
596                 if ( s.complete ) {
597                         s.complete.call( s.context, xhr, status );
598                 }
599
600                 // The request was completed
601                 if ( s.global ) {
602                         jQuery.ajax.triggerGlobal( s, "ajaxComplete", [xhr, s] );
603                 }
604
605                 // Handle the global AJAX counter
606                 if ( s.global && jQuery.ajax.active-- === 1 ) {
607                         jQuery.event.trigger( "ajaxStop" );
608                 }
609         },
610                 
611         triggerGlobal: function( s, type, args ) {
612                 (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args);
613         },
614
615         // Determines if an XMLHttpRequest was successful or not
616         httpSuccess: function( xhr ) {
617                 try {
618                         // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
619                         return !xhr.status && location.protocol === "file:" ||
620                                 // Opera returns 0 when status is 304
621                                 ( xhr.status >= 200 && xhr.status < 300 ) ||
622                                 xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
623                 } catch(e) {}
624
625                 return false;
626         },
627
628         // Determines if an XMLHttpRequest returns NotModified
629         httpNotModified: function( xhr, url ) {
630                 var lastModified = xhr.getResponseHeader("Last-Modified"),
631                         etag = xhr.getResponseHeader("Etag");
632
633                 if ( lastModified ) {
634                         jQuery.lastModified[url] = lastModified;
635                 }
636
637                 if ( etag ) {
638                         jQuery.etag[url] = etag;
639                 }
640
641                 // Opera returns 0 when status is 304
642                 return xhr.status === 304 || xhr.status === 0;
643         },
644
645         httpData: function( xhr, type, s ) {
646                 var ct = xhr.getResponseHeader("content-type") || "",
647                         xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
648                         data = xml ? xhr.responseXML : xhr.responseText;
649
650                 if ( xml && data.documentElement.nodeName === "parsererror" ) {
651                         jQuery.error( "parsererror" );
652                 }
653
654                 // Allow a pre-filtering function to sanitize the response
655                 // s is checked to keep backwards compatibility
656                 if ( s && s.dataFilter ) {
657                         data = s.dataFilter( data, type );
658                 }
659
660                 // The filter can actually parse the response
661                 if ( typeof data === "string" ) {
662                         // Get the JavaScript object, if JSON is used.
663                         if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
664                                 data = jQuery.parseJSON( data );
665
666                         // If the type is "script", eval it in global context
667                         } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
668                                 jQuery.globalEval( data );
669                         }
670                 }
671
672                 return data;
673         }
674
675 });