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