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