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