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