Fixed a bug in event - "native" is a reserved word in Safari 2.
[jquery.git] / src / ajax / 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 \r       serializeArray: function() {\r
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){\r                        var val = jQuery(this).val();
78                         return val == null ? null :
79                                 val.constructor == Array ?
80                                         jQuery.map( val, function(i, val){\r                                             return {name: elem.name, value: val};
81                                         }) :
82                                         {name: elem.name, value: val};\r
83                 }).get();\r      }
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                 // Break the data into one single string
164                 var q = s.url.indexOf("?");
165                 if ( q > -1 ) {
166                         s.data = (s.data ? s.data + "&" : "") + s.url.slice(q + 1);
167                         s.url = s.url.slice(0, q);
168                 }
169
170                 // Handle JSONP Parameter Callbacks
171                 if ( s.dataType == "jsonp" ) {
172                         if ( !s.data || !s.data.match(jsre) )
173                                 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
174                         s.dataType = "json";
175                 }
176
177                 // Build temporary JSONP function
178                 if ( s.dataType == "json" && s.data && s.data.match(jsre) ) {
179                         jsonp = "jsonp" + jsc++;
180                         s.data = s.data.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                                 // Garbage collect
191                                 window[ jsonp ] = undefined;
192                                 try{ delete window[ jsonp ]; } catch(e){}
193                         };
194                 }
195
196                 if ( s.dataType == "script" && s.cache == null )
197                         s.cache = false;
198
199                 if ( s.cache === false && s.type.toLowerCase() == "get" )
200                         s.data = (s.data ? s.data + "&" : "") + "_=" + (new Date()).getTime();
201
202                 // If data is available, append data to url for get requests
203                 if ( s.data && s.type.toLowerCase() == "get" ) {
204                         s.url += "?" + s.data;
205
206                         // IE likes to send both get and post data, prevent this
207                         s.data = null;
208                 }
209
210                 // Watch for a new set of requests
211                 if ( s.global && ! jQuery.active++ )
212                         jQuery.event.trigger( "ajaxStart" );
213
214                 // If we're requesting a remote document
215                 // and trying to load JSON or Script
216                 if ( !s.url.indexOf("http") && s.dataType == "script" ) {
217                         var script = document.createElement("script");
218                         script.src = s.url;
219
220                         // Handle Script loading
221                         if ( !jsonp && (s.success || s.complete) ) {
222                                 var done = false;
223
224                                 // Attach handlers for all browsers
225                                 script.onload = script.onreadystatechange = function(){
226                                         if ( !done && (!this.readyState || 
227                                                         this.readyState == "loaded" || this.readyState == "complete") ) {
228                                                 done = true;
229                                                 success();
230                                                 complete();
231                                                 document.body.removeChild( script );
232                                         }
233                                 };
234                         }
235
236                         document.body.appendChild(script);
237
238                         // We handle everything using the script element injection
239                         return;
240                 }
241
242                 var requestDone = false;
243
244                 // Create the request object; Microsoft failed to properly
245                 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
246                 var xml = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
247
248                 // Open the socket
249                 xml.open(s.type, s.url, s.async);
250
251                 // Set the correct header, if data is being sent
252                 if ( s.data )
253                         xml.setRequestHeader("Content-Type", s.contentType);
254
255                 // Set the If-Modified-Since header, if ifModified mode.
256                 if ( s.ifModified )
257                         xml.setRequestHeader("If-Modified-Since",
258                                 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
259
260                 // Set header so the called script knows that it's an XMLHttpRequest
261                 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
262
263                 // Allow custom headers/mimetypes
264                 if ( s.beforeSend )
265                         s.beforeSend(xml);
266                         
267                 if ( s.global )
268                     jQuery.event.trigger("ajaxSend", [xml, s]);
269
270                 // Wait for a response to come back
271                 var onreadystatechange = function(isTimeout){
272                         // The transfer is complete and the data is available, or the request timed out
273                         if ( !requestDone && xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
274                                 requestDone = true;
275                                 
276                                 // clear poll interval
277                                 if (ival) {
278                                         clearInterval(ival);
279                                         ival = null;
280                                 }
281                                 
282                                 status = isTimeout == "timeout" && "timeout" ||
283                                         !jQuery.httpSuccess( xml ) && "error" ||
284                                         s.ifModified && jQuery.httpNotModified( xml, s.url ) && "notmodified" ||
285                                         "success";
286
287                                 if ( status == "success" ) {
288                                         // Watch for, and catch, XML document parse errors
289                                         try {
290                                                 // process the data (runs the xml through httpData regardless of callback)
291                                                 data = jQuery.httpData( xml, s.dataType );
292                                         } catch(e) {
293                                                 status = "parsererror";
294                                         }
295                                 }
296
297                                 // Make sure that the request was successful or notmodified
298                                 if ( status == "success" ) {
299                                         // Cache Last-Modified header, if ifModified mode.
300                                         var modRes;
301                                         try {
302                                                 modRes = xml.getResponseHeader("Last-Modified");
303                                         } catch(e) {} // swallow exception thrown by FF if header is not available
304         
305                                         if ( s.ifModified && modRes )
306                                                 jQuery.lastModified[s.url] = modRes;
307
308                                         // JSONP handles its own success callback
309                                         if ( !jsonp )
310                                                 success();      
311                                 } else
312                                         jQuery.handleError(s, xml, status);
313
314                                 // Fire the complete handlers
315                                 complete();
316
317                                 // Stop memory leaks
318                                 if ( s.async )
319                                         xml = null;
320                         }
321                 };
322                 
323                 if ( s.async ) {
324                         // don't attach the handler to the request, just poll it instead
325                         var ival = setInterval(onreadystatechange, 13); 
326
327                         // Timeout checker
328                         if ( s.timeout > 0 )
329                                 setTimeout(function(){
330                                         // Check to see if the request is still happening
331                                         if ( xml ) {
332                                                 // Cancel the request
333                                                 xml.abort();
334         
335                                                 if( !requestDone )
336                                                         onreadystatechange( "timeout" );
337                                         }
338                                 }, s.timeout);
339                 }
340                         
341                 // Send the data
342                 try {
343                         xml.send(s.data);
344                 } catch(e) {
345                         jQuery.handleError(s, xml, null, e);
346                 }
347                 
348                 // firefox 1.5 doesn't fire statechange for sync requests
349                 if ( !s.async )
350                         onreadystatechange();
351                 
352                 // return XMLHttpRequest to allow aborting the request etc.
353                 return xml;
354
355                 function success(){
356                         // If a local callback was specified, fire it and pass it the data
357                         if ( s.success )
358                                 s.success( data, status );
359
360                         // Fire the global callback
361                         if ( s.global )
362                                 jQuery.event.trigger( "ajaxSuccess", [xml, s] );
363                 }
364
365                 function complete(){
366                         // Process result
367                         if ( s.complete )
368                                 s.complete(xml, status);
369
370                         // The request was completed
371                         if ( s.global )
372                                 jQuery.event.trigger( "ajaxComplete", [xml, s] );
373
374                         // Handle the global AJAX counter
375                         if ( s.global && ! --jQuery.active )
376                                 jQuery.event.trigger( "ajaxStop" );
377                 }
378         },
379
380         handleError: function( s, xml, status, e ) {
381                 // If a local callback was specified, fire it
382                 if ( s.error ) s.error( xml, status, e );
383
384                 // Fire the global callback
385                 if ( s.global )
386                         jQuery.event.trigger( "ajaxError", [xml, s, e] );
387         },
388
389         // Counter for holding the number of active queries
390         active: 0,
391
392         // Determines if an XMLHttpRequest was successful or not
393         httpSuccess: function( r ) {
394                 try {
395                         return !r.status && location.protocol == "file:" ||
396                                 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
397                                 jQuery.browser.safari && r.status == undefined;
398                 } catch(e){}
399                 return false;
400         },
401
402         // Determines if an XMLHttpRequest returns NotModified
403         httpNotModified: function( xml, url ) {
404                 try {
405                         var xmlRes = xml.getResponseHeader("Last-Modified");
406
407                         // Firefox always returns 200. check Last-Modified date
408                         return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
409                                 jQuery.browser.safari && xml.status == undefined;
410                 } catch(e){}
411                 return false;
412         },
413
414         httpData: function( r, type ) {
415                 var ct = r.getResponseHeader("content-type");
416                 var xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0;
417                 var data = xml ? r.responseXML : r.responseText;
418
419                 if ( xml && data.documentElement.tagName == "parsererror" )
420                         throw "parsererror";
421
422                 // If the type is "script", eval it in global context
423                 if ( type == "script" )
424                         jQuery.globalEval( data );
425
426                 // Get the JavaScript object, if JSON is used.
427                 if ( type == "json" )
428                         data = eval("(" + data + ")");
429
430                 return data;
431         },
432
433         // Serialize an array of form elements or a set of
434         // key/values into a query string
435         param: function( a ) {
436                 var s = [];
437
438                 // If an array was passed in, assume that it is an array
439                 // of form elements
440                 if ( a.constructor == Array || a.jquery )
441                         // Serialize the form elements
442                         jQuery.each( a, function(){
443                                 s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
444                         });
445
446                 // Otherwise, assume that it's an object of key/value pairs
447                 else
448                         // Serialize the key/values
449                         for ( var j in a )
450                                 // If the value is an array then the key names need to be repeated
451                                 if ( a[j] && a[j].constructor == Array )
452                                         jQuery.each( a[j], function(){
453                                                 s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
454                                         });
455                                 else
456                                         s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j] ) );
457
458                 // Return the resulting serialization
459                 return s.join("&").replace(/%20/g, "+");
460         }
461
462 });