jquery ajax: closes #4994. Adding 'context' setting to $.ajax
[jquery.git] / src / ajax.js
1 var jsc = now(),
2         rscript = /<script(.|\s)*?\/script>/g,
3         rselectTextarea = /select|textarea/i,
4         rinput = /text|hidden|password|search/i,
5         jsre = /=\?(&|$)/,
6         rquery = /\?/,
7         rts = /(\?|&)_=.*?(&|$)/,
8         rurl = /^(\w+:)?\/\/([^\/?#]+)/,
9         r20 = /%20/g;
10
11 jQuery.fn.extend({
12         // Keep a copy of the old load
13         _load: jQuery.fn.load,
14
15         load: function( url, params, callback ) {
16                 if ( typeof url !== "string" ) {
17                         return this._load( url );
18                 }
19
20                 var off = url.indexOf(" ");
21                 if ( off >= 0 ) {
22                         var selector = url.slice(off, url.length);
23                         url = url.slice(0, off);
24                 }
25
26                 // Default to a GET request
27                 var type = "GET";
28
29                 // If the second parameter was provided
30                 if ( params ) {
31                         // If it's a function
32                         if ( jQuery.isFunction( params ) ) {
33                                 // We assume that it's the callback
34                                 callback = params;
35                                 params = null;
36
37                         // Otherwise, build a param string
38                         } else if ( typeof params === "object" ) {
39                                 params = jQuery.param( params );
40                                 type = "POST";
41                         }
42                 }
43
44                 // Request the remote document
45                 jQuery.ajax({
46                         url: url,
47                         type: type,
48                         dataType: "html",
49                         data: params,
50                         context:this,
51                         complete: function(res, status){
52                                 // If successful, inject the HTML into all the matched elements
53                                 if ( status === "success" || status === "notmodified" ) {
54                                         // See if a selector was specified
55                                         this.html( selector ?
56                                                 // Create a dummy div to hold the results
57                                                 jQuery("<div />")
58                                                         // inject the contents of the document in, removing the scripts
59                                                         // to avoid any 'Permission Denied' errors in IE
60                                                         .append(res.responseText.replace(rscript, ""))
61
62                                                         // Locate the specified elements
63                                                         .find(selector) :
64
65                                                 // If not, just inject the full result
66                                                 res.responseText );
67                                 }
68
69                                 if ( callback ) {
70                                         this.each( callback, [res.responseText, status, res] );
71                                 }
72                         }
73                 });
74
75                 return this;
76         },
77
78         serialize: function() {
79                 return jQuery.param(this.serializeArray());
80         },
81         serializeArray: function() {
82                 return this.map(function(){
83                         return this.elements ? jQuery.makeArray(this.elements) : this;
84                 })
85                 .filter(function(){
86                         return this.name && !this.disabled &&
87                                 (this.checked || rselectTextarea.test(this.nodeName) ||
88                                         rinput.test(this.type));
89                 })
90                 .map(function(i, elem){
91                         var val = jQuery(this).val();
92
93                         return val == null ?
94                                 null :
95                                 jQuery.isArray(val) ?
96                                         jQuery.map( val, function(val, i){
97                                                 return {name: elem.name, value: val};
98                                         }) :
99                                         {name: elem.name, value: val};
100                 }).get();
101         }
102 });
103
104 // Attach a bunch of functions for handling common AJAX events
105 jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
106         jQuery.fn[o] = function(f){
107                 return this.bind(o, f);
108         };
109 });
110
111 jQuery.extend({
112
113         get: function( url, data, callback, type ) {
114                 // shift arguments if data argument was ommited
115                 if ( jQuery.isFunction( data ) ) {
116                         callback = data;
117                         data = null;
118                 }
119
120                 return jQuery.ajax({
121                         type: "GET",
122                         url: url,
123                         data: data,
124                         success: callback,
125                         dataType: type
126                 });
127         },
128
129         getScript: function( url, callback ) {
130                 return jQuery.get(url, null, callback, "script");
131         },
132
133         getJSON: function( url, data, callback ) {
134                 return jQuery.get(url, data, callback, "json");
135         },
136
137         post: function( url, data, callback, type ) {
138                 if ( jQuery.isFunction( data ) ) {
139                         callback = data;
140                         data = {};
141                 }
142
143                 return jQuery.ajax({
144                         type: "POST",
145                         url: url,
146                         data: data,
147                         success: callback,
148                         dataType: type
149                 });
150         },
151
152         ajaxSetup: function( settings ) {
153                 jQuery.extend( jQuery.ajaxSettings, settings );
154         },
155
156         ajaxSettings: {
157                 url: location.href,
158                 global: true,
159                 type: "GET",
160                 contentType: "application/x-www-form-urlencoded",
161                 processData: true,
162                 async: true,
163                 /*
164                 timeout: 0,
165                 data: null,
166                 username: null,
167                 password: null,
168                 */
169                 // Create the request object; Microsoft failed to properly
170                 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
171                 // This function can be overriden by calling jQuery.ajaxSetup
172                 xhr: function(){
173                         return window.ActiveXObject ?
174                                 new ActiveXObject("Microsoft.XMLHTTP") :
175                                 new XMLHttpRequest();
176                 },
177                 accepts: {
178                         xml: "application/xml, text/xml",
179                         html: "text/html",
180                         script: "text/javascript, application/javascript",
181                         json: "application/json, text/javascript",
182                         text: "text/plain",
183                         _default: "*/*"
184                 }
185         },
186
187         // Last-Modified header cache for next request
188         lastModified: {},
189         etag: {},
190
191         ajax: function( s ) {
192                 // Extend the settings, but re-extend 's' so that it can be
193                 // checked again later (in the test suite, specifically)
194                 s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
195                 
196                 var jsonp, status, data,
197                         callbackContext = s.context || window,
198                         type = s.type.toUpperCase();
199
200                 // convert data if not already a string
201                 if ( s.data && s.processData && typeof s.data !== "string" ) {
202                         s.data = jQuery.param(s.data);
203                 }
204
205                 // Handle JSONP Parameter Callbacks
206                 if ( s.dataType === "jsonp" ) {
207                         if ( type === "GET" ) {
208                                 if ( !jsre.test( s.url ) ) {
209                                         s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
210                                 }
211                         } else if ( !s.data || !jsre.test(s.data) ) {
212                                 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
213                         }
214                         s.dataType = "json";
215                 }
216
217                 // Build temporary JSONP function
218                 if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
219                         jsonp = "jsonp" + jsc++;
220
221                         // Replace the =? sequence both in the query string and the data
222                         if ( s.data ) {
223                                 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
224                         }
225
226                         s.url = s.url.replace(jsre, "=" + jsonp + "$1");
227
228                         // We need to make sure
229                         // that a JSONP style response is executed properly
230                         s.dataType = "script";
231
232                         // Handle JSONP-style loading
233                         window[ jsonp ] = function(tmp){
234                                 data = tmp;
235                                 success();
236                                 complete();
237                                 // Garbage collect
238                                 window[ jsonp ] = undefined;
239                                 try{ delete window[ jsonp ]; } catch(e){}
240                                 if ( head ) {
241                                         head.removeChild( script );
242                                 }
243                         };
244                 }
245
246                 if ( s.dataType === "script" && s.cache === null ) {
247                         s.cache = false;
248                 }
249
250                 if ( s.cache === false && type === "GET" ) {
251                         var ts = now();
252
253                         // try replacing _= if it is there
254                         var ret = s.url.replace(rts, "$1_=" + ts + "$2");
255
256                         // if nothing was replaced, add timestamp to the end
257                         s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
258                 }
259
260                 // If data is available, append data to url for get requests
261                 if ( s.data && type === "GET" ) {
262                         s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
263                 }
264
265                 // Watch for a new set of requests
266                 if ( s.global && ! jQuery.active++ ) {
267                         jQuery.event.trigger( "ajaxStart" );
268                 }
269
270                 // Matches an absolute URL, and saves the domain
271                 var parts = rurl.exec( s.url );
272
273                 // If we're requesting a remote document
274                 // and trying to load JSON or Script with a GET
275                 if ( s.dataType === "script" && type === "GET" && parts
276                         && ( parts[1] && parts[1] !== location.protocol || parts[2] !== location.host )) {
277
278                         var head = document.getElementsByTagName("head")[0] || document.documentElement;
279                         var script = document.createElement("script");
280                         script.src = s.url;
281                         if ( s.scriptCharset ) {
282                                 script.charset = s.scriptCharset;
283                         }
284
285                         // Handle Script loading
286                         if ( !jsonp ) {
287                                 var done = false;
288
289                                 // Attach handlers for all browsers
290                                 script.onload = script.onreadystatechange = function(){
291                                         if ( !done && (!this.readyState ||
292                                                         this.readyState === "loaded" || this.readyState === "complete") ) {
293                                                 done = true;
294                                                 success();
295                                                 complete();
296
297                                                 // Handle memory leak in IE
298                                                 script.onload = script.onreadystatechange = null;
299                                                 if ( head && script.parentNode ) {
300                                                         head.removeChild( script );
301                                                 }
302                                         }
303                                 };
304                         }
305
306                         // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
307                         // This arises when a base node is used (#2709 and #4378).
308                         head.insertBefore( script, head.firstChild );
309
310                         // We handle everything using the script element injection
311                         return undefined;
312                 }
313
314                 var requestDone = false;
315
316                 // Create the request object
317                 var xhr = s.xhr();
318
319                 // Open the socket
320                 // Passing null username, generates a login popup on Opera (#2865)
321                 if ( s.username ) {
322                         xhr.open(type, s.url, s.async, s.username, s.password);
323                 } else {
324                         xhr.open(type, s.url, s.async);
325                 }
326
327                 // Need an extra try/catch for cross domain requests in Firefox 3
328                 try {
329                         // Set the correct header, if data is being sent
330                         if ( s.data ) {
331                                 xhr.setRequestHeader("Content-Type", s.contentType);
332                         }
333
334                                 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
335                                 if ( s.ifModified ) {
336                                         if ( jQuery.lastModified[s.url] ) {
337                                                 xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
338                                         }
339
340                                         if ( jQuery.etag[s.url] ) {
341                                                 xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
342                                         }
343                                 }
344
345                         // Set header so the called script knows that it's an XMLHttpRequest
346                         xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
347
348                         // Set the Accepts header for the server, depending on the dataType
349                         xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
350                                 s.accepts[ s.dataType ] + ", */*" :
351                                 s.accepts._default );
352                 } catch(e){}
353
354                 // Allow custom headers/mimetypes and early abort
355                 if ( s.beforeSend && s.beforeSend.call(callbackContext, xhr, s) === false ) {
356                         // Handle the global AJAX counter
357                         if ( s.global && ! --jQuery.active ) {
358                                 jQuery.event.trigger( "ajaxStop" );
359                         }
360
361                         // close opended socket
362                         xhr.abort();
363                         return false;
364                 }
365
366                 if ( s.global ) {
367                         trigger("ajaxSend", [xhr, s]);
368                 }
369
370                 // Wait for a response to come back
371                 var onreadystatechange = function(isTimeout){
372                         // The request was aborted, clear the interval and decrement jQuery.active
373                         if ( !xhr || xhr.readyState === 0 ) {
374                                 if ( ival ) {
375                                         // clear poll interval
376                                         clearInterval( ival );
377                                         ival = null;
378
379                                         // Handle the global AJAX counter
380                                         if ( s.global && ! --jQuery.active ) {
381                                                 jQuery.event.trigger( "ajaxStop" );
382                                         }
383                                 }
384
385                         // The transfer is complete and the data is available, or the request timed out
386                         } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
387                                 requestDone = true;
388
389                                 // clear poll interval
390                                 if (ival) {
391                                         clearInterval(ival);
392                                         ival = null;
393                                 }
394
395                                 status = isTimeout === "timeout" ?
396                                         "timeout" :
397                                         !jQuery.httpSuccess( xhr ) ?
398                                                 "error" :
399                                                 s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
400                                                         "notmodified" :
401                                                         "success";
402
403                                 if ( status === "success" ) {
404                                         // Watch for, and catch, XML document parse errors
405                                         try {
406                                                 // process the data (runs the xml through httpData regardless of callback)
407                                                 data = jQuery.httpData( xhr, s.dataType, s );
408                                         } catch(e) {
409                                                 status = "parsererror";
410                                         }
411                                 }
412
413                                 // Make sure that the request was successful or notmodified
414                                 if ( status === "success" || status === "notmodified" ) {
415                                         // JSONP handles its own success callback
416                                         if ( !jsonp ) {
417                                                 success();
418                                         }
419                                 } else {
420                                         jQuery.handleError(s, xhr, status);
421                                 }
422
423                                 // Fire the complete handlers
424                                 complete();
425
426                                 if ( isTimeout ) {
427                                         xhr.abort();
428                                 }
429
430                                 // Stop memory leaks
431                                 if ( s.async ) {
432                                         xhr = null;
433                                 }
434                         }
435                 };
436
437                 if ( s.async ) {
438                         // don't attach the handler to the request, just poll it instead
439                         var ival = setInterval(onreadystatechange, 13);
440
441                         // Timeout checker
442                         if ( s.timeout > 0 ) {
443                                 setTimeout(function(){
444                                         // Check to see if the request is still happening
445                                         if ( xhr && !requestDone ) {
446                                                 onreadystatechange( "timeout" );
447                                         }
448                                 }, s.timeout);
449                         }
450                 }
451
452                 // Send the data
453                 try {
454                         xhr.send( type === "POST" || type === "PUT" ? s.data : null );
455                 } catch(e) {
456                         jQuery.handleError(s, xhr, null, e);
457                 }
458
459                 // firefox 1.5 doesn't fire statechange for sync requests
460                 if ( !s.async ) {
461                         onreadystatechange();
462                 }
463
464                 function success(){
465                         // If a local callback was specified, fire it and pass it the data
466                         if ( s.success ) {
467                                 s.success.call( callbackContext, data, status );
468                         }
469
470                         // Fire the global callback
471                         if ( s.global ) {
472                                 trigger( "ajaxSuccess", [xhr, s] );
473                         }
474                 }
475
476                 function complete(){
477                         // Process result
478                         if ( s.complete ) {
479                                 s.complete.call( callbackContext, xhr, status);
480                         }
481
482                         // The request was completed
483                         if ( s.global ) {
484                                 trigger( "ajaxComplete", [xhr, s] );
485                         }
486
487                         // Handle the global AJAX counter
488                         if ( s.global && ! --jQuery.active ) {
489                                 jQuery.event.trigger( "ajaxStop" );
490                         }
491                 }
492                 
493                 function trigger(type, args){
494                         (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args);
495                 }
496
497                 // return XMLHttpRequest to allow aborting the request etc.
498                 return xhr;
499         },
500
501         handleError: function( s, xhr, status, e ) {
502                 // If a local callback was specified, fire it
503                 if ( s.error ) {
504                         s.error.call( s.context || window, xhr, status, e );
505                 }
506
507                 // Fire the global callback
508                 if ( s.global ) {
509                         (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
510                 }
511         },
512
513         // Counter for holding the number of active queries
514         active: 0,
515
516         // Determines if an XMLHttpRequest was successful or not
517         httpSuccess: function( xhr ) {
518                 try {
519                         // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
520                         return !xhr.status && location.protocol === "file:" ||
521                                 // Opera returns 0 when status is 304
522                                 ( xhr.status >= 200 && xhr.status < 300 ) ||
523                                 xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
524                 } catch(e){}
525
526                 return false;
527         },
528
529         // Determines if an XMLHttpRequest returns NotModified
530         httpNotModified: function( xhr, url ) {
531                 var lastModified = xhr.getResponseHeader("Last-Modified"),
532                         etag = xhr.getResponseHeader("Etag");
533
534                 if ( lastModified ) {
535                         jQuery.lastModified[url] = lastModified;
536                 }
537
538                 if ( etag ) {
539                         jQuery.etag[url] = etag;
540                 }
541
542                 // Opera returns 0 when status is 304
543                 return xhr.status === 304 || xhr.status === 0;
544         },
545
546         httpData: function( xhr, type, s ) {
547                 var ct = xhr.getResponseHeader("content-type"),
548                         xml = type === "xml" || !type && ct && ct.indexOf("xml") >= 0,
549                         data = xml ? xhr.responseXML : xhr.responseText;
550
551                 if ( xml && data.documentElement.nodeName === "parsererror" ) {
552                         throw "parsererror";
553                 }
554
555                 // Allow a pre-filtering function to sanitize the response
556                 // s is checked to keep backwards compatibility
557                 if ( s && s.dataFilter ) {
558                         data = s.dataFilter( data, type );
559                 }
560
561                 // The filter can actually parse the response
562                 if ( typeof data === "string" ) {
563
564                         // If the type is "script", eval it in global context
565                         if ( type === "script" ) {
566                                 jQuery.globalEval( data );
567                         }
568
569                         // Get the JavaScript object, if JSON is used.
570                         if ( type === "json" ) {
571                                 if ( typeof JSON === "object" && JSON.parse ) {
572                                         data = JSON.parse( data );
573                                 } else {
574                                         data = (new Function("return " + data))();
575                                 }
576                         }
577                 }
578
579                 return data;
580         },
581
582         // Serialize an array of form elements or a set of
583         // key/values into a query string
584         param: function( a ) {
585                 var s = [];
586
587                 function add( key, value ){
588                         s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
589                 }
590
591                 // If an array was passed in, assume that it is an array
592                 // of form elements
593                 if ( jQuery.isArray(a) || a.jquery ) {
594                         // Serialize the form elements
595                         jQuery.each( a, function() {
596                                 add( this.name, this.value );
597                         });
598                 } else {
599                         // Recursively encode parameters from object, 
600                         // building a prefix path as we go down
601                         function buildParams(obj, prefix)
602                         {
603                                 if ( jQuery.isArray(obj) ) {
604                                         for ( var i = 0, length = obj.length; i < length; i++ ) {
605                                                 buildParams( obj[i], prefix );
606                                         };
607                                 } else if( typeof(obj) == "object" ) {
608                                         for ( var j in obj ) {
609                                                 var postfix = ((j.indexOf("[]") > 0) ? "[]" : ""); // move any brackets to the end
610                                                 buildParams(obj[j], (prefix ? (prefix+"["+j.replace("[]", "")+"]"+postfix) : j) );
611                                         }
612                                 } else {
613                                         add( prefix, jQuery.isFunction(obj) ? obj() : obj );
614                                 }
615                         }
616                         buildParams(a);
617                 }
618
619                 // Return the resulting serialization
620                 return s.join("&").replace(r20, "+");
621         }
622
623 });