Moved the RegExp in ajax.js out from inline, goes towards ticket #4111.
[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                 var self = this;
45
46                 // Request the remote document
47                 jQuery.ajax({
48                         url: url,
49                         type: type,
50                         dataType: "html",
51                         data: params,
52                         complete: function(res, status){
53                                 // If successful, inject the HTML into all the matched elements
54                                 if ( status === "success" || status === "notmodified" ) {
55                                         // See if a selector was specified
56                                         self.html( selector ?
57                                                 // Create a dummy div to hold the results
58                                                 jQuery("<div/>")
59                                                         // inject the contents of the document in, removing the scripts
60                                                         // to avoid any 'Permission Denied' errors in IE
61                                                         .append(res.responseText.replace(rscript, ""))
62
63                                                         // Locate the specified elements
64                                                         .find(selector) :
65
66                                                 // If not, just inject the full result
67                                                 res.responseText );
68                                 }
69
70                                 if ( callback ) {
71                                         self.each( callback, [res.responseText, status, res] );
72                                 }
73                         }
74                 });
75
76                 return this;
77         },
78
79         serialize: function() {
80                 return jQuery.param(this.serializeArray());
81         },
82         serializeArray: function() {
83                 return this.map(function(){
84                         return this.elements ? jQuery.makeArray(this.elements) : this;
85                 })
86                 .filter(function(){
87                         return this.name && !this.disabled &&
88                                 (this.checked || rselectTextarea.test(this.nodeName) ||
89                                         rinput.test(this.type));
90                 })
91                 .map(function(i, elem){
92                         var val = jQuery(this).val();
93
94                         return val == null ?
95                                 null :
96                                 jQuery.isArray(val) ?
97                                         jQuery.map( val, function(val, i){
98                                                 return {name: elem.name, value: val};
99                                         }) :
100                                         {name: elem.name, value: val};
101                 }).get();
102         }
103 });
104
105 // Attach a bunch of functions for handling common AJAX events
106 jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
107         jQuery.fn[o] = function(f){
108                 return this.bind(o, f);
109         };
110 });
111
112 jQuery.extend({
113
114         get: function( url, data, callback, type ) {
115                 // shift arguments if data argument was ommited
116                 if ( jQuery.isFunction( data ) ) {
117                         callback = data;
118                         data = null;
119                 }
120
121                 return jQuery.ajax({
122                         type: "GET",
123                         url: url,
124                         data: data,
125                         success: callback,
126                         dataType: type
127                 });
128         },
129
130         getScript: function( url, callback ) {
131                 return jQuery.get(url, null, callback, "script");
132         },
133
134         getJSON: function( url, data, callback ) {
135                 return jQuery.get(url, data, callback, "json");
136         },
137
138         post: function( url, data, callback, type ) {
139                 if ( jQuery.isFunction( data ) ) {
140                         callback = data;
141                         data = {};
142                 }
143
144                 return jQuery.ajax({
145                         type: "POST",
146                         url: url,
147                         data: data,
148                         success: callback,
149                         dataType: type
150                 });
151         },
152
153         ajaxSetup: function( settings ) {
154                 jQuery.extend( jQuery.ajaxSettings, settings );
155         },
156
157         ajaxSettings: {
158                 url: location.href,
159                 global: true,
160                 type: "GET",
161                 contentType: "application/x-www-form-urlencoded",
162                 processData: true,
163                 async: true,
164                 /*
165                 timeout: 0,
166                 data: null,
167                 username: null,
168                 password: null,
169                 */
170                 // Create the request object; Microsoft failed to properly
171                 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
172                 // This function can be overriden by calling jQuery.ajaxSetup
173                 xhr: function(){
174                         return window.ActiveXObject ?
175                                 new ActiveXObject("Microsoft.XMLHTTP") :
176                                 new XMLHttpRequest();
177                 },
178                 accepts: {
179                         xml: "application/xml, text/xml",
180                         html: "text/html",
181                         script: "text/javascript, application/javascript",
182                         json: "application/json, text/javascript",
183                         text: "text/plain",
184                         _default: "*/*"
185                 }
186         },
187
188         // Last-Modified header cache for next request
189         lastModified: {},
190         etag: {},
191
192         ajax: function( s ) {
193                 // Extend the settings, but re-extend 's' so that it can be
194                 // checked again later (in the test suite, specifically)
195                 s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
196
197                 var jsonp, status, data,
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];
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                                                 head.removeChild( script );
300                                         }
301                                 };
302                         }
303
304                         // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
305                         // This arises when a base node is used (#2709 and #4378).
306                         head.insertBefore( script, head.firstChild );
307
308                         // We handle everything using the script element injection
309                         return undefined;
310                 }
311
312                 var requestDone = false;
313
314                 // Create the request object
315                 var xhr = s.xhr();
316
317                 // Open the socket
318                 // Passing null username, generates a login popup on Opera (#2865)
319                 if ( s.username ) {
320                         xhr.open(type, s.url, s.async, s.username, s.password);
321                 } else {
322                         xhr.open(type, s.url, s.async);
323                 }
324
325                 // Need an extra try/catch for cross domain requests in Firefox 3
326                 try {
327                         // Set the correct header, if data is being sent
328                         if ( s.data ) {
329                                 xhr.setRequestHeader("Content-Type", s.contentType);
330                         }
331
332                                 // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
333                                 if ( s.ifModified ) {
334                                         if ( jQuery.lastModified[s.url] ) {
335                                                 xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
336                                         }
337
338                                         if ( jQuery.etag[s.url] ) {
339                                                 xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
340                                         }
341                                 }
342
343                         // Set header so the called script knows that it's an XMLHttpRequest
344                         xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
345
346                         // Set the Accepts header for the server, depending on the dataType
347                         xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
348                                 s.accepts[ s.dataType ] + ", */*" :
349                                 s.accepts._default );
350                 } catch(e){}
351
352                 // Allow custom headers/mimetypes and early abort
353                 if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
354                         // Handle the global AJAX counter
355                         if ( s.global && ! --jQuery.active ) {
356                                 jQuery.event.trigger( "ajaxStop" );
357                         }
358
359                         // close opended socket
360                         xhr.abort();
361                         return false;
362                 }
363
364                 if ( s.global ) {
365                         jQuery.event.trigger("ajaxSend", [xhr, s]);
366                 }
367
368                 // Wait for a response to come back
369                 var onreadystatechange = function(isTimeout){
370                         // The request was aborted, clear the interval and decrement jQuery.active
371                         if ( xhr.readyState === 0 ) {
372                                 if ( ival ) {
373                                         // clear poll interval
374                                         clearInterval( ival );
375                                         ival = null;
376
377                                         // Handle the global AJAX counter
378                                         if ( s.global && ! --jQuery.active ) {
379                                                 jQuery.event.trigger( "ajaxStop" );
380                                         }
381                                 }
382
383                         // The transfer is complete and the data is available, or the request timed out
384                         } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
385                                 requestDone = true;
386
387                                 // clear poll interval
388                                 if (ival) {
389                                         clearInterval(ival);
390                                         ival = null;
391                                 }
392
393                                 status = isTimeout === "timeout" ?
394                                         "timeout" :
395                                         !jQuery.httpSuccess( xhr ) ?
396                                                 "error" :
397                                                 s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
398                                                         "notmodified" :
399                                                         "success";
400
401                                 if ( status === "success" ) {
402                                         // Watch for, and catch, XML document parse errors
403                                         try {
404                                                 // process the data (runs the xml through httpData regardless of callback)
405                                                 data = jQuery.httpData( xhr, s.dataType, s );
406                                         } catch(e) {
407                                                 status = "parsererror";
408                                         }
409                                 }
410
411                                 // Make sure that the request was successful or notmodified
412                                 if ( status === "success" || status === "notmodified" ) {
413                                         // JSONP handles its own success callback
414                                         if ( !jsonp ) {
415                                                 success();
416                                         }
417                                 } else {
418                                         jQuery.handleError(s, xhr, status);
419                                 }
420
421                                 // Fire the complete handlers
422                                 complete();
423
424                                 if ( isTimeout ) {
425                                         xhr.abort();
426                                 }
427
428                                 // Stop memory leaks
429                                 if ( s.async ) {
430                                         xhr = null;
431                                 }
432                         }
433                 };
434
435                 if ( s.async ) {
436                         // don't attach the handler to the request, just poll it instead
437                         var ival = setInterval(onreadystatechange, 13);
438
439                         // Timeout checker
440                         if ( s.timeout > 0 ) {
441                                 setTimeout(function(){
442                                         // Check to see if the request is still happening
443                                         if ( xhr && !requestDone ) {
444                                                 onreadystatechange( "timeout" );
445                                         }
446                                 }, s.timeout);
447                         }
448                 }
449
450                 // Send the data
451                 try {
452                         xhr.send( type === "POST" ? s.data : null );
453                 } catch(e) {
454                         jQuery.handleError(s, xhr, null, e);
455                 }
456
457                 // firefox 1.5 doesn't fire statechange for sync requests
458                 if ( !s.async ) {
459                         onreadystatechange();
460                 }
461
462                 function success(){
463                         // If a local callback was specified, fire it and pass it the data
464                         if ( s.success ) {
465                                 s.success( data, status );
466                         }
467
468                         // Fire the global callback
469                         if ( s.global ) {
470                                 jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
471                         }
472                 }
473
474                 function complete(){
475                         // Process result
476                         if ( s.complete ) {
477                                 s.complete(xhr, status);
478                         }
479
480                         // The request was completed
481                         if ( s.global ) {
482                                 jQuery.event.trigger( "ajaxComplete", [xhr, s] );
483                         }
484
485                         // Handle the global AJAX counter
486                         if ( s.global && ! --jQuery.active ) {
487                                 jQuery.event.trigger( "ajaxStop" );
488                         }
489                 }
490
491                 // return XMLHttpRequest to allow aborting the request etc.
492                 return xhr;
493         },
494
495         handleError: function( s, xhr, status, e ) {
496                 // If a local callback was specified, fire it
497                 if ( s.error ) {
498                         s.error( xhr, status, e );
499                 }
500
501                 // Fire the global callback
502                 if ( s.global ) {
503                         jQuery.event.trigger( "ajaxError", [xhr, s, e] );
504                 }
505         },
506
507         // Counter for holding the number of active queries
508         active: 0,
509
510         // Determines if an XMLHttpRequest was successful or not
511         httpSuccess: function( xhr ) {
512                 try {
513                         // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
514                         return !xhr.status && location.protocol === "file:" ||
515                                 // Opera returns 0 when status is 304
516                                 ( xhr.status >= 200 && xhr.status < 300 ) ||
517                                 xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
518                 } catch(e){}
519
520                 return false;
521         },
522
523         // Determines if an XMLHttpRequest returns NotModified
524         httpNotModified: function( xhr, url ) {
525                 var last_modified = xhr.getResponseHeader("Last-Modified"),
526                         etag = xhr.getResponseHeader("Etag");
527
528                 if ( last_modified ) {
529                         jQuery.lastModified[url] = last_modified;
530                 }
531
532                 if ( etag ) {
533                         jQuery.etag[url] = etag;
534                 }
535
536                 // Opera returns 0 when status is 304
537                 return xhr.status === 304 || xhr.status === 0;
538         },
539
540         httpData: function( xhr, type, s ) {
541                 var ct = xhr.getResponseHeader("content-type"),
542                         xml = type === "xml" || !type && ct && ct.indexOf("xml") >= 0,
543                         data = xml ? xhr.responseXML : xhr.responseText;
544
545                 if ( xml && data.documentElement.nodeName === "parsererror" ) {
546                         throw "parsererror";
547                 }
548
549                 // Allow a pre-filtering function to sanitize the response
550                 // s is checked to keep backwards compatibility
551                 if ( s && s.dataFilter ) {
552                         data = s.dataFilter( data, type );
553                 }
554
555                 // The filter can actually parse the response
556                 if ( typeof data === "string" ) {
557
558                         // If the type is "script", eval it in global context
559                         if ( type === "script" ) {
560                                 jQuery.globalEval( data );
561                         }
562
563                         // Get the JavaScript object, if JSON is used.
564                         if ( type === "json" ) {
565                                 if ( typeof JSON === "object" && JSON.parse ) {
566                                         data = JSON.parse( data );
567                                 } else {
568                                         data = (new Function("return " + data))();
569                                 }
570                         }
571                 }
572
573                 return data;
574         },
575
576         // Serialize an array of form elements or a set of
577         // key/values into a query string
578         param: function( a ) {
579                 var s = [];
580
581                 function add( key, value ){
582                         s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
583                 }
584
585                 // If an array was passed in, assume that it is an array
586                 // of form elements
587                 if ( jQuery.isArray(a) || a.jquery ) {
588                         // Serialize the form elements
589                         jQuery.each( a, function(){
590                                 add( this.name, this.value );
591                         });
592
593                 // Otherwise, assume that it's an object of key/value pairs
594                 } else {
595                         // Serialize the key/values
596                         for ( var j in a ) {
597                                 // If the value is an array then the key names need to be repeated
598                                 if ( jQuery.isArray(a[j]) ) {
599                                         jQuery.each( a[j], function(){
600                                                 add( j, this );
601                                         });
602                                 } else {
603                                         add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );
604                                 }
605                         }
606                 }
607
608                 // Return the resulting serialization
609                 return s.join("&").replace(r20, "+");
610         }
611
612 });