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