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