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