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