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