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