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