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