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