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