Adds support for username and password to $.ajax
[jquery.git] / src / ajax.js
1 jQuery.fn.extend({
2         load: function( url, params, callback ) {
3                 if ( jQuery.isFunction( url ) )
4                         return this.bind("load", url);
5
6                 var off = url.indexOf(" ");
7                 if ( off >= 0 ) {
8                         var selector = url.slice(off, url.length);
9                         url = url.slice(0, off);
10                 }
11
12                 callback = callback || function(){};
13
14                 // Default to a GET request
15                 var type = "GET";
16
17                 // If the second parameter was provided
18                 if ( params )
19                         // If it's a function
20                         if ( jQuery.isFunction( params ) ) {
21                                 // We assume that it's the callback
22                                 callback = params;
23                                 params = null;
24
25                         // Otherwise, build a param string
26                         } else {
27                                 params = jQuery.param( params );
28                                 type = "POST";
29                         }
30
31                 var self = this;
32
33                 // Request the remote document
34                 jQuery.ajax({
35                         url: url,
36                         type: type,
37                         dataType: "html",
38                         data: params,
39                         complete: function(res, status){
40                                 // If successful, inject the HTML into all the matched elements
41                                 if ( status == "success" || status == "notmodified" )
42                                         // See if a selector was specified
43                                         self.html( selector ?
44                                                 // Create a dummy div to hold the results
45                                                 jQuery("<div/>")
46                                                         // inject the contents of the document in, removing the scripts
47                                                         // to avoid any 'Permission Denied' errors in IE
48                                                         .append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
49
50                                                         // Locate the specified elements
51                                                         .find(selector) :
52
53                                                 // If not, just inject the full result
54                                                 res.responseText );
55
56                                 self.each( callback, [res.responseText, status, res] );
57                         }
58                 });
59                 return this;
60         },
61
62         serialize: function() {
63                 return jQuery.param(this.serializeArray());
64         },
65         serializeArray: function() {
66                 return this.map(function(){
67                         return jQuery.nodeName(this, "form") ?
68                                 jQuery.makeArray(this.elements) : this;
69                 })
70                 .filter(function(){
71                         return this.name && !this.disabled && 
72                                 (this.checked || /select|textarea/i.test(this.nodeName) || 
73                                         /text|hidden|password/i.test(this.type));
74                 })
75                 .map(function(i, elem){
76                         var val = jQuery(this).val();
77                         return val == null ? null :
78                                 val.constructor == Array ?
79                                         jQuery.map( val, function(val, i){
80                                                 return {name: elem.name, value: val};
81                                         }) :
82                                         {name: elem.name, value: val};
83                 }).get();
84         }
85 });
86
87 // Attach a bunch of functions for handling common AJAX events
88 jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
89         jQuery.fn[o] = function(f){
90                 return this.bind(o, f);
91         };
92 });
93
94 var jsc = (new Date).getTime();
95
96 jQuery.extend({
97         get: function( url, data, callback, type ) {
98                 // shift arguments if data argument was ommited
99                 if ( jQuery.isFunction( data ) ) {
100                         callback = data;
101                         data = null;
102                 }
103                 
104                 return jQuery.ajax({
105                         type: "GET",
106                         url: url,
107                         data: data,
108                         success: callback,
109                         dataType: type
110                 });
111         },
112
113         getScript: function( url, callback ) {
114                 return jQuery.get(url, null, callback, "script");
115         },
116
117         getJSON: function( url, data, callback ) {
118                 return jQuery.get(url, data, callback, "json");
119         },
120
121         post: function( url, data, callback, type ) {
122                 if ( jQuery.isFunction( data ) ) {
123                         callback = data;
124                         data = {};
125                 }
126
127                 return jQuery.ajax({
128                         type: "POST",
129                         url: url,
130                         data: data,
131                         success: callback,
132                         dataType: type
133                 });
134         },
135
136         ajaxSetup: function( settings ) {
137                 jQuery.extend( jQuery.ajaxSettings, settings );
138         },
139
140         ajaxSettings: {
141                 global: true,
142                 type: "GET",
143                 timeout: 0,
144                 contentType: "application/x-www-form-urlencoded",
145                 processData: true,
146                 async: true,
147                 data: null,
148                 username: null,
149                 password: null
150         },
151         
152         // Last-Modified header cache for next request
153         lastModified: {},
154
155         ajax: function( s ) {
156                 var jsonp, jsre = /=\?(&|$)/g, status, data;
157
158                 // Extend the settings, but re-extend 's' so that it can be
159                 // checked again later (in the test suite, specifically)
160                 s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
161
162                 // convert data if not already a string
163                 if ( s.data && s.processData && typeof s.data != "string" )
164                         s.data = jQuery.param(s.data);
165
166                 // Handle JSONP Parameter Callbacks
167                 if ( s.dataType == "jsonp" ) {
168                         if ( s.type.toLowerCase() == "get" ) {
169                                 if ( !s.url.match(jsre) )
170                                         s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
171                         } else if ( !s.data || !s.data.match(jsre) )
172                                 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
173                         s.dataType = "json";
174                 }
175
176                 // Build temporary JSONP function
177                 if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
178                         jsonp = "jsonp" + jsc++;
179
180                         // Replace the =? sequence both in the query string and the data
181                         if ( s.data )
182                                 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
183                         s.url = s.url.replace(jsre, "=" + jsonp + "$1");
184
185                         // We need to make sure
186                         // that a JSONP style response is executed properly
187                         s.dataType = "script";
188
189                         // Handle JSONP-style loading
190                         window[ jsonp ] = function(tmp){
191                                 data = tmp;
192                                 success();
193                                 complete();
194                                 // Garbage collect
195                                 window[ jsonp ] = undefined;
196                                 try{ delete window[ jsonp ]; } catch(e){}
197                                 if ( head )
198                                         head.removeChild( script );
199                         };
200                 }
201
202                 if ( s.dataType == "script" && s.cache == null )
203                         s.cache = false;
204
205                 if ( s.cache === false && s.type.toLowerCase() == "get" ) {
206                         var ts = (new Date()).getTime();
207                         // try replacing _= if it is there
208                         var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
209                         // if nothing was replaced, add timestamp to the end
210                         s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
211                 }
212
213                 // If data is available, append data to url for get requests
214                 if ( s.data && s.type.toLowerCase() == "get" ) {
215                         s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;
216
217                         // IE likes to send both get and post data, prevent this
218                         s.data = null;
219                 }
220
221                 // Watch for a new set of requests
222                 if ( s.global && ! jQuery.active++ )
223                         jQuery.event.trigger( "ajaxStart" );
224
225                 // If we're requesting a remote document
226                 // and trying to load JSON or Script with a GET
227                 if ( (!s.url.indexOf("http") || !s.url.indexOf("//")) && ( s.dataType == "script" || s.dataType =="json" ) && s.type.toLowerCase() == "get" ) {
228                         var head = document.getElementsByTagName("head")[0];
229                         var script = document.createElement("script");
230                         script.src = s.url;
231                         if (s.scriptCharset)
232                                 script.charset = s.scriptCharset;
233
234                         // Handle Script loading
235                         if ( !jsonp ) {
236                                 var done = false;
237
238                                 // Attach handlers for all browsers
239                                 script.onload = script.onreadystatechange = function(){
240                                         if ( !done && (!this.readyState || 
241                                                         this.readyState == "loaded" || this.readyState == "complete") ) {
242                                                 done = true;
243                                                 success();
244                                                 complete();
245                                                 head.removeChild( script );
246                                         }
247                                 };
248                         }
249
250                         head.appendChild(script);
251
252                         // We handle everything using the script element injection
253                         return undefined;
254                 }
255
256                 var requestDone = false;
257
258                 // Create the request object; Microsoft failed to properly
259                 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
260                 var xml = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
261
262                 // Open the socket
263                 xml.open(s.type, s.url, s.async, s.username, s.password);
264
265                 // Need an extra try/catch for cross domain requests in Firefox 3
266                 try {
267                         // Set the correct header, if data is being sent
268                         if ( s.data )
269                                 xml.setRequestHeader("Content-Type", s.contentType);
270
271                         // Set the If-Modified-Since header, if ifModified mode.
272                         if ( s.ifModified )
273                                 xml.setRequestHeader("If-Modified-Since",
274                                         jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
275
276                         // Set header so the called script knows that it's an XMLHttpRequest
277                         xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
278                 } catch(e){}
279
280                 // Allow custom headers/mimetypes
281                 if ( s.beforeSend )
282                         s.beforeSend(xml);
283                         
284                 if ( s.global )
285                         jQuery.event.trigger("ajaxSend", [xml, s]);
286
287                 // Wait for a response to come back
288                 var onreadystatechange = function(isTimeout){
289                         // The transfer is complete and the data is available, or the request timed out
290                         if ( !requestDone && xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
291                                 requestDone = true;
292                                 
293                                 // clear poll interval
294                                 if (ival) {
295                                         clearInterval(ival);
296                                         ival = null;
297                                 }
298                                 
299                                 status = isTimeout == "timeout" && "timeout" ||
300                                         !jQuery.httpSuccess( xml ) && "error" ||
301                                         s.ifModified && jQuery.httpNotModified( xml, s.url ) && "notmodified" ||
302                                         "success";
303
304                                 if ( status == "success" ) {
305                                         // Watch for, and catch, XML document parse errors
306                                         try {
307                                                 // process the data (runs the xml through httpData regardless of callback)
308                                                 data = jQuery.httpData( xml, s.dataType );
309                                         } catch(e) {
310                                                 status = "parsererror";
311                                         }
312                                 }
313
314                                 // Make sure that the request was successful or notmodified
315                                 if ( status == "success" ) {
316                                         // Cache Last-Modified header, if ifModified mode.
317                                         var modRes;
318                                         try {
319                                                 modRes = xml.getResponseHeader("Last-Modified");
320                                         } catch(e) {} // swallow exception thrown by FF if header is not available
321         
322                                         if ( s.ifModified && modRes )
323                                                 jQuery.lastModified[s.url] = modRes;
324
325                                         // JSONP handles its own success callback
326                                         if ( !jsonp )
327                                                 success();      
328                                 } else
329                                         jQuery.handleError(s, xml, status);
330
331                                 // Fire the complete handlers
332                                 complete();
333
334                                 // Stop memory leaks
335                                 if ( s.async )
336                                         xml = null;
337                         }
338                 };
339                 
340                 if ( s.async ) {
341                         // don't attach the handler to the request, just poll it instead
342                         var ival = setInterval(onreadystatechange, 13); 
343
344                         // Timeout checker
345                         if ( s.timeout > 0 )
346                                 setTimeout(function(){
347                                         // Check to see if the request is still happening
348                                         if ( xml ) {
349                                                 // Cancel the request
350                                                 xml.abort();
351         
352                                                 if( !requestDone )
353                                                         onreadystatechange( "timeout" );
354                                         }
355                                 }, s.timeout);
356                 }
357                         
358                 // Send the data
359                 try {
360                         xml.send(s.data);
361                 } catch(e) {
362                         jQuery.handleError(s, xml, null, e);
363                 }
364                 
365                 // firefox 1.5 doesn't fire statechange for sync requests
366                 if ( !s.async )
367                         onreadystatechange();
368
369                 function success(){
370                         // If a local callback was specified, fire it and pass it the data
371                         if ( s.success )
372                                 s.success( data, status );
373
374                         // Fire the global callback
375                         if ( s.global )
376                                 jQuery.event.trigger( "ajaxSuccess", [xml, s] );
377                 }
378
379                 function complete(){
380                         // Process result
381                         if ( s.complete )
382                                 s.complete(xml, status);
383
384                         // The request was completed
385                         if ( s.global )
386                                 jQuery.event.trigger( "ajaxComplete", [xml, s] );
387
388                         // Handle the global AJAX counter
389                         if ( s.global && ! --jQuery.active )
390                                 jQuery.event.trigger( "ajaxStop" );
391                 }
392                 
393                 // return XMLHttpRequest to allow aborting the request etc.
394                 return xml;
395         },
396
397         handleError: function( s, xml, status, e ) {
398                 // If a local callback was specified, fire it
399                 if ( s.error ) s.error( xml, status, e );
400
401                 // Fire the global callback
402                 if ( s.global )
403                         jQuery.event.trigger( "ajaxError", [xml, s, e] );
404         },
405
406         // Counter for holding the number of active queries
407         active: 0,
408
409         // Determines if an XMLHttpRequest was successful or not
410         httpSuccess: function( r ) {
411                 try {
412                         // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
413                         return !r.status && location.protocol == "file:" ||
414                                 ( r.status >= 200 && r.status < 300 ) || r.status == 304 || r.status == 1223 ||
415                                 jQuery.browser.safari && r.status == undefined;
416                 } catch(e){}
417                 return false;
418         },
419
420         // Determines if an XMLHttpRequest returns NotModified
421         httpNotModified: function( xml, url ) {
422                 try {
423                         var xmlRes = xml.getResponseHeader("Last-Modified");
424
425                         // Firefox always returns 200. check Last-Modified date
426                         return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
427                                 jQuery.browser.safari && xml.status == undefined;
428                 } catch(e){}
429                 return false;
430         },
431
432         httpData: function( r, type ) {
433                 var ct = r.getResponseHeader("content-type");
434                 var xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0;
435                 var data = xml ? r.responseXML : r.responseText;
436
437                 if ( xml && data.documentElement.tagName == "parsererror" )
438                         throw "parsererror";
439
440                 // If the type is "script", eval it in global context
441                 if ( type == "script" )
442                         jQuery.globalEval( data );
443
444                 // Get the JavaScript object, if JSON is used.
445                 if ( type == "json" )
446                         data = eval("(" + data + ")");
447
448                 return data;
449         },
450
451         // Serialize an array of form elements or a set of
452         // key/values into a query string
453         param: function( a ) {
454                 var s = [];
455
456                 // If an array was passed in, assume that it is an array
457                 // of form elements
458                 if ( a.constructor == Array || a.jquery )
459                         // Serialize the form elements
460                         jQuery.each( a, function(){
461                                 s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
462                         });
463
464                 // Otherwise, assume that it's an object of key/value pairs
465                 else
466                         // Serialize the key/values
467                         for ( var j in a )
468                                 // If the value is an array then the key names need to be repeated
469                                 if ( a[j] && a[j].constructor == Array )
470                                         jQuery.each( a[j], function(){
471                                                 s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
472                                         });
473                                 else
474                                         s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j] ) );
475
476                 // Return the resulting serialization
477                 return s.join("&").replace(/%20/g, "+");
478         }
479
480 });