Bug #1584, ajaxStop/complete calls weren't called for JSONP requests.
[jquery.git] / src / ajax.js
1 jQuery.fn.extend({
2         load: function( url, params, callback ) {
3                 if ( jQuery.isFunction( url ) )
4                         return this.bind("load", url);
5
6                 var off = url.indexOf(" ");
7                 if ( off >= 0 ) {
8                         var selector = url.slice(off, url.length);
9                         url = url.slice(0, off);
10                 }
11
12                 callback = callback || function(){};
13
14                 // Default to a GET request
15                 var type = "GET";
16
17                 // If the second parameter was provided
18                 if ( params )
19                         // If it's a function
20                         if ( jQuery.isFunction( params ) ) {
21                                 // We assume that it's the callback
22                                 callback = params;
23                                 params = null;
24
25                         // Otherwise, build a param string
26                         } else {
27                                 params = jQuery.param( params );
28                                 type = "POST";
29                         }
30
31                 var self = this;
32
33                 // Request the remote document
34                 jQuery.ajax({
35                         url: url,
36                         type: type,
37                         data: params,
38                         complete: function(res, status){
39                                 // If successful, inject the HTML into all the matched elements
40                                 if ( status == "success" || status == "notmodified" )
41                                         // See if a selector was specified
42                                         self.html( selector ?
43                                                 // Create a dummy div to hold the results
44                                                 jQuery("<div/>")
45                                                         // inject the contents of the document in, removing the scripts
46                                                         // to avoid any 'Permission Denied' errors in IE
47                                                         .append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
48
49                                                         // Locate the specified elements
50                                                         .find(selector) :
51
52                                                 // If not, just inject the full result
53                                                 res.responseText );
54
55                                 // Add delay to account for Safari's delay in globalEval
56                                 setTimeout(function(){
57                                         self.each( callback, [res.responseText, status, res] );
58                                 }, 13);
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 jQuery.nodeName(this, "form") ?
70                                 jQuery.makeArray(this.elements) : this;
71                 })
72                 .filter(function(){
73                         return this.name && !this.disabled && 
74                                 (this.checked || /select|textarea/i.test(this.nodeName) || 
75                                         /text|hidden|password/i.test(this.type));
76                 })
77                 .map(function(i, elem){
78                         var val = jQuery(this).val();
79                         return val == null ? null :
80                                 val.constructor == Array ?
81                                         jQuery.map( val, function(val, i){
82                                                 return {name: elem.name, value: val};
83                                         }) :
84                                         {name: elem.name, value: val};
85                 }).get();
86         }
87 });
88
89 // Attach a bunch of functions for handling common AJAX events
90 jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
91         jQuery.fn[o] = function(f){
92                 return this.bind(o, f);
93         };
94 });
95
96 var jsc = (new Date).getTime();
97
98 jQuery.extend({
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                 global: true,
144                 type: "GET",
145                 timeout: 0,
146                 contentType: "application/x-www-form-urlencoded",
147                 processData: true,
148                 async: true,
149                 data: null
150         },
151         
152         // Last-Modified header cache for next request
153         lastModified: {},
154
155         ajax: function( s ) {
156                 var jsonp, jsre = /=(\?|%3F)/g, status, data;
157
158                 // Extend the settings, but re-extend 's' so that it can be
159                 // checked again later (in the test suite, specifically)
160                 s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
161
162                 // convert data if not already a string
163                 if ( s.data && s.processData && typeof s.data != "string" )
164                         s.data = jQuery.param(s.data);
165
166                 // Break the data into one single string
167                 var q = s.url.indexOf("?");
168                 if ( q > -1 ) {
169                         s.data = (s.data ? s.data + "&" : "") + s.url.slice(q + 1);
170                         s.url = s.url.slice(0, q);
171                 }
172
173                 // Handle JSONP Parameter Callbacks
174                 if ( s.dataType == "jsonp" ) {
175                         if ( !s.data || !s.data.match(jsre) )
176                                 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
177                         s.dataType = "json";
178                 }
179
180                 // Build temporary JSONP function
181                 if ( s.dataType == "json" && s.data && s.data.match(jsre) ) {
182                         jsonp = "jsonp" + jsc++;
183                         s.data = s.data.replace(jsre, "=" + jsonp);
184
185                         // We need to make sure
186                         // that a JSONP style response is executed properly
187                         s.dataType = "script";
188
189                         // Handle JSONP-style loading
190                         window[ jsonp ] = function(tmp){
191                                 data = tmp;
192                                 success();
193                                 complete();
194                                 // Garbage collect
195                                 window[ jsonp ] = undefined;
196                                 try{ delete window[ jsonp ]; } catch(e){}
197                         };
198                 }
199
200                 if ( s.dataType == "script" && s.cache == null )
201                         s.cache = false;
202
203                 if ( s.cache === false && s.type.toLowerCase() == "get" )
204                         s.data = (s.data ? s.data + "&" : "") + "_=" + (new Date()).getTime();
205
206                 // If data is available, append data to url for get requests
207                 if ( s.data && s.type.toLowerCase() == "get" ) {
208                         s.url += "?" + s.data;
209
210                         // IE likes to send both get and post data, prevent this
211                         s.data = null;
212                 }
213
214                 // Watch for a new set of requests
215                 if ( s.global && ! jQuery.active++ )
216                         jQuery.event.trigger( "ajaxStart" );
217
218                 // If we're requesting a remote document
219                 // and trying to load JSON or Script
220                 if ( !s.url.indexOf("http") && s.dataType == "script" ) {
221                         var head = document.getElementsByTagName("head")[0];
222                         var script = document.createElement("script");
223                         script.src = s.url;
224
225                         // Handle Script loading
226                         if ( !jsonp && (s.success || s.complete) ) {
227                                 var done = false;
228
229                                 // Attach handlers for all browsers
230                                 script.onload = script.onreadystatechange = function(){
231                                         if ( !done && (!this.readyState || 
232                                                         this.readyState == "loaded" || this.readyState == "complete") ) {
233                                                 done = true;
234                                                 success();
235                                                 complete();
236                                                 head.removeChild( script );
237                                         }
238                                 };
239                         }
240
241                         head.appendChild(script);
242
243                         // We handle everything using the script element injection
244                         return;
245                 }
246
247                 var requestDone = false;
248
249                 // Create the request object; Microsoft failed to properly
250                 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
251                 var xml = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
252
253                 // Open the socket
254                 xml.open(s.type, s.url, s.async);
255
256                 // Set the correct header, if data is being sent
257                 if ( s.data )
258                         xml.setRequestHeader("Content-Type", s.contentType);
259
260                 // Set the If-Modified-Since header, if ifModified mode.
261                 if ( s.ifModified )
262                         xml.setRequestHeader("If-Modified-Since",
263                                 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
264
265                 // Set header so the called script knows that it's an XMLHttpRequest
266                 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
267
268                 // Allow custom headers/mimetypes
269                 if ( s.beforeSend )
270                         s.beforeSend(xml);
271                         
272                 if ( s.global )
273                     jQuery.event.trigger("ajaxSend", [xml, s]);
274
275                 // Wait for a response to come back
276                 var onreadystatechange = function(isTimeout){
277                         // The transfer is complete and the data is available, or the request timed out
278                         if ( !requestDone && xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
279                                 requestDone = true;
280                                 
281                                 // clear poll interval
282                                 if (ival) {
283                                         clearInterval(ival);
284                                         ival = null;
285                                 }
286                                 
287                                 status = isTimeout == "timeout" && "timeout" ||
288                                         !jQuery.httpSuccess( xml ) && "error" ||
289                                         s.ifModified && jQuery.httpNotModified( xml, s.url ) && "notmodified" ||
290                                         "success";
291
292                                 if ( status == "success" ) {
293                                         // Watch for, and catch, XML document parse errors
294                                         try {
295                                                 // process the data (runs the xml through httpData regardless of callback)
296                                                 data = jQuery.httpData( xml, s.dataType );
297                                         } catch(e) {
298                                                 status = "parsererror";
299                                         }
300                                 }
301
302                                 // Make sure that the request was successful or notmodified
303                                 if ( status == "success" ) {
304                                         // Cache Last-Modified header, if ifModified mode.
305                                         var modRes;
306                                         try {
307                                                 modRes = xml.getResponseHeader("Last-Modified");
308                                         } catch(e) {} // swallow exception thrown by FF if header is not available
309         
310                                         if ( s.ifModified && modRes )
311                                                 jQuery.lastModified[s.url] = modRes;
312
313                                         // JSONP handles its own success callback
314                                         if ( !jsonp )
315                                                 success();      
316                                 } else
317                                         jQuery.handleError(s, xml, status);
318
319                                 // Fire the complete handlers
320                                 complete();
321
322                                 // Stop memory leaks
323                                 if ( s.async )
324                                         xml = null;
325                         }
326                 };
327                 
328                 if ( s.async ) {
329                         // don't attach the handler to the request, just poll it instead
330                         var ival = setInterval(onreadystatechange, 13); 
331
332                         // Timeout checker
333                         if ( s.timeout > 0 )
334                                 setTimeout(function(){
335                                         // Check to see if the request is still happening
336                                         if ( xml ) {
337                                                 // Cancel the request
338                                                 xml.abort();
339         
340                                                 if( !requestDone )
341                                                         onreadystatechange( "timeout" );
342                                         }
343                                 }, s.timeout);
344                 }
345                         
346                 // Send the data
347                 try {
348                         xml.send(s.data);
349                 } catch(e) {
350                         jQuery.handleError(s, xml, null, e);
351                 }
352                 
353                 // firefox 1.5 doesn't fire statechange for sync requests
354                 if ( !s.async )
355                         onreadystatechange();
356                 
357                 // return XMLHttpRequest to allow aborting the request etc.
358                 return xml;
359
360                 function success(){
361                         // If a local callback was specified, fire it and pass it the data
362                         if ( s.success )
363                                 s.success( data, status );
364
365                         // Fire the global callback
366                         if ( s.global )
367                                 jQuery.event.trigger( "ajaxSuccess", [xml, s] );
368                 }
369
370                 function complete(){
371                         // Process result
372                         if ( s.complete )
373                                 s.complete(xml, status);
374
375                         // The request was completed
376                         if ( s.global )
377                                 jQuery.event.trigger( "ajaxComplete", [xml, s] );
378
379                         // Handle the global AJAX counter
380                         if ( s.global && ! --jQuery.active )
381                                 jQuery.event.trigger( "ajaxStop" );
382                 }
383         },
384
385         handleError: function( s, xml, status, e ) {
386                 // If a local callback was specified, fire it
387                 if ( s.error ) s.error( xml, status, e );
388
389                 // Fire the global callback
390                 if ( s.global )
391                         jQuery.event.trigger( "ajaxError", [xml, s, e] );
392         },
393
394         // Counter for holding the number of active queries
395         active: 0,
396
397         // Determines if an XMLHttpRequest was successful or not
398         httpSuccess: function( r ) {
399                 try {
400                         return !r.status && location.protocol == "file:" ||
401                                 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
402                                 jQuery.browser.safari && r.status == undefined;
403                 } catch(e){}
404                 return false;
405         },
406
407         // Determines if an XMLHttpRequest returns NotModified
408         httpNotModified: function( xml, url ) {
409                 try {
410                         var xmlRes = xml.getResponseHeader("Last-Modified");
411
412                         // Firefox always returns 200. check Last-Modified date
413                         return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
414                                 jQuery.browser.safari && xml.status == undefined;
415                 } catch(e){}
416                 return false;
417         },
418
419         httpData: function( r, type ) {
420                 var ct = r.getResponseHeader("content-type");
421                 var xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0;
422                 var data = xml ? r.responseXML : r.responseText;
423
424                 if ( xml && data.documentElement.tagName == "parsererror" )
425                         throw "parsererror";
426
427                 // If the type is "script", eval it in global context
428                 if ( type == "script" )
429                         jQuery.globalEval( data );
430
431                 // Get the JavaScript object, if JSON is used.
432                 if ( type == "json" )
433                         data = eval("(" + data + ")");
434
435                 return data;
436         },
437
438         // Serialize an array of form elements or a set of
439         // key/values into a query string
440         param: function( a ) {
441                 var s = [];
442
443                 // If an array was passed in, assume that it is an array
444                 // of form elements
445                 if ( a.constructor == Array || a.jquery )
446                         // Serialize the form elements
447                         jQuery.each( a, function(){
448                                 s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
449                         });
450
451                 // Otherwise, assume that it's an object of key/value pairs
452                 else
453                         // Serialize the key/values
454                         for ( var j in a )
455                                 // If the value is an array then the key names need to be repeated
456                                 if ( a[j] && a[j].constructor == Array )
457                                         jQuery.each( a[j], function(){
458                                                 s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
459                                         });
460                                 else
461                                         s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j] ) );
462
463                 // Return the resulting serialization
464                 return s.join("&").replace(/%20/g, "+");
465         }
466
467 });