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