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