Provided detailed message for JSON parse errors. Fixes #4435.
[jquery.git] / src / ajax.js
1 var jsc = now(),
2         rscript = /<script(.|\s)*?\/script>/gi,
3         rselectTextarea = /select|textarea/i,
4         rinput = /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,
5         jsre = /=\?(&|$)/,
6         rquery = /\?/,
7         rts = /(\?|&)_=.*?(&|$)/,
8         rurl = /^(\w+:)?\/\/([^\/?#]+)/,
9         r20 = /%20/g;
10
11 jQuery.fn.extend({
12         // Keep a copy of the old load
13         _load: jQuery.fn.load,
14
15         load: function( url, params, callback ) {
16                 if ( typeof url !== "string" ) {
17                         return this._load( url );
18
19                 // Don't do a request if no elements are being requested
20                 } else if ( !this.length ) {
21                         return this;
22                 }
23
24                 var off = url.indexOf(" ");
25                 if ( off >= 0 ) {
26                         var selector = url.slice(off, url.length);
27                         url = url.slice(0, off);
28                 }
29
30                 // Default to a GET request
31                 var type = "GET";
32
33                 // If the second parameter was provided
34                 if ( params ) {
35                         // If it's a function
36                         if ( jQuery.isFunction( params ) ) {
37                                 // We assume that it's the callback
38                                 callback = params;
39                                 params = null;
40
41                         // Otherwise, build a param string
42                         } else if ( typeof params === "object" ) {
43                                 params = jQuery.param( params, jQuery.ajaxSettings.traditional );
44                                 type = "POST";
45                         }
46                 }
47
48                 var self = this;
49
50                 // Request the remote document
51                 jQuery.ajax({
52                         url: url,
53                         type: type,
54                         dataType: "html",
55                         data: params,
56                         complete: function( res, status ) {
57                                 // If successful, inject the HTML into all the matched elements
58                                 if ( status === "success" || status === "notmodified" ) {
59                                         // See if a selector was specified
60                                         self.html( selector ?
61                                                 // Create a dummy div to hold the results
62                                                 jQuery("<div />")
63                                                         // inject the contents of the document in, removing the scripts
64                                                         // to avoid any 'Permission Denied' errors in IE
65                                                         .append(res.responseText.replace(rscript, ""))
66
67                                                         // Locate the specified elements
68                                                         .find(selector) :
69
70                                                 // If not, just inject the full result
71                                                 res.responseText );
72                                 }
73
74                                 if ( callback ) {
75                                         self.each( callback, [res.responseText, status, res] );
76                                 }
77                         }
78                 });
79
80                 return this;
81         },
82
83         serialize: function() {
84                 return jQuery.param(this.serializeArray());
85         },
86         serializeArray: function() {
87                 return this.map(function() {
88                         return this.elements ? jQuery.makeArray(this.elements) : this;
89                 })
90                 .filter(function() {
91                         return this.name && !this.disabled &&
92                                 (this.checked || rselectTextarea.test(this.nodeName) ||
93                                         rinput.test(this.type));
94                 })
95                 .map(function( i, elem ) {
96                         var val = jQuery(this).val();
97
98                         return val == null ?
99                                 null :
100                                 jQuery.isArray(val) ?
101                                         jQuery.map( val, function( val, i ) {
102                                                 return { name: elem.name, value: val };
103                                         }) :
104                                         { name: elem.name, value: val };
105                 }).get();
106         }
107 });
108
109 // Attach a bunch of functions for handling common AJAX events
110 jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) {
111         jQuery.fn[o] = function( f ) {
112                 return this.bind(o, f);
113         };
114 });
115
116 jQuery.extend({
117
118         get: function( url, data, callback, type ) {
119                 // shift arguments if data argument was omited
120                 if ( jQuery.isFunction( data ) ) {
121                         type = type || callback;
122                         callback = data;
123                         data = null;
124                 }
125
126                 return jQuery.ajax({
127                         type: "GET",
128                         url: url,
129                         data: data,
130                         success: callback,
131                         dataType: type
132                 });
133         },
134
135         getScript: function( url, callback ) {
136                 return jQuery.get(url, null, callback, "script");
137         },
138
139         getJSON: function( url, data, callback ) {
140                 return jQuery.get(url, data, callback, "json");
141         },
142
143         post: function( url, data, callback, type ) {
144                 // shift arguments if data argument was omited
145                 if ( jQuery.isFunction( data ) ) {
146                         type = type || callback;
147                         callback = data;
148                         data = {};
149                 }
150
151                 return jQuery.ajax({
152                         type: "POST",
153                         url: url,
154                         data: data,
155                         success: callback,
156                         dataType: type
157                 });
158         },
159
160         ajaxSetup: function( settings ) {
161                 jQuery.extend( jQuery.ajaxSettings, settings );
162         },
163
164         ajaxSettings: {
165                 url: location.href,
166                 global: true,
167                 type: "GET",
168                 contentType: "application/x-www-form-urlencoded",
169                 processData: true,
170                 async: true,
171                 /*
172                 timeout: 0,
173                 data: null,
174                 username: null,
175                 password: null,
176                 traditional: false,
177                 */
178                 // Create the request object; Microsoft failed to properly
179                 // implement the XMLHttpRequest in IE7 (can't request local files),
180                 // so we use the ActiveXObject when it is available
181                 // This function can be overriden by calling jQuery.ajaxSetup
182                 xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ?
183                         function() {
184                                 return new window.XMLHttpRequest();
185                         } :
186                         function() {
187                                 try {
188                                         return new window.ActiveXObject("Microsoft.XMLHTTP");
189                                 } catch(e) {}
190                         },
191                 accepts: {
192                         xml: "application/xml, text/xml",
193                         html: "text/html",
194                         script: "text/javascript, application/javascript",
195                         json: "application/json, text/javascript",
196                         text: "text/plain",
197                         _default: "*/*"
198                 }
199         },
200
201         // Last-Modified header cache for next request
202         lastModified: {},
203         etag: {},
204
205         ajax: function( origSettings ) {
206                 var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings);
207                 
208                 var jsonp, status, data,
209                         callbackContext = origSettings && origSettings.context || s,
210                         type = s.type.toUpperCase();
211
212                 // convert data if not already a string
213                 if ( s.data && s.processData && typeof s.data !== "string" ) {
214                         s.data = jQuery.param( s.data, s.traditional );
215                 }
216
217                 // Handle JSONP Parameter Callbacks
218                 if ( s.dataType === "jsonp" ) {
219                         if ( type === "GET" ) {
220                                 if ( !jsre.test( s.url ) ) {
221                                         s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
222                                 }
223                         } else if ( !s.data || !jsre.test(s.data) ) {
224                                 s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
225                         }
226                         s.dataType = "json";
227                 }
228
229                 // Build temporary JSONP function
230                 if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
231                         jsonp = s.jsonpCallback || ("jsonp" + jsc++);
232
233                         // Replace the =? sequence both in the query string and the data
234                         if ( s.data ) {
235                                 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
236                         }
237
238                         s.url = s.url.replace(jsre, "=" + jsonp + "$1");
239
240                         // We need to make sure
241                         // that a JSONP style response is executed properly
242                         s.dataType = "script";
243
244                         // Handle JSONP-style loading
245                         window[ jsonp ] = window[ jsonp ] || function( tmp ) {
246                                 data = tmp;
247                                 success();
248                                 complete();
249                                 // Garbage collect
250                                 window[ jsonp ] = undefined;
251
252                                 try {
253                                         delete window[ jsonp ];
254                                 } catch(e) {}
255
256                                 if ( head ) {
257                                         head.removeChild( script );
258                                 }
259                         };
260                 }
261
262                 if ( s.dataType === "script" && s.cache === null ) {
263                         s.cache = false;
264                 }
265
266                 if ( s.cache === false && type === "GET" ) {
267                         var ts = now();
268
269                         // try replacing _= if it is there
270                         var ret = s.url.replace(rts, "$1_=" + ts + "$2");
271
272                         // if nothing was replaced, add timestamp to the end
273                         s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
274                 }
275
276                 // If data is available, append data to url for get requests
277                 if ( s.data && type === "GET" ) {
278                         s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
279                 }
280
281                 // Watch for a new set of requests
282                 if ( s.global && ! jQuery.active++ ) {
283                         jQuery.event.trigger( "ajaxStart" );
284                 }
285
286                 // Matches an absolute URL, and saves the domain
287                 var parts = rurl.exec( s.url ),
288                         remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
289
290                 // If we're requesting a remote document
291                 // and trying to load JSON or Script with a GET
292                 if ( s.dataType === "script" && type === "GET" && remote ) {
293                         var head = document.getElementsByTagName("head")[0] || document.documentElement;
294                         var script = document.createElement("script");
295                         script.src = s.url;
296                         if ( s.scriptCharset ) {
297                                 script.charset = s.scriptCharset;
298                         }
299
300                         // Handle Script loading
301                         if ( !jsonp ) {
302                                 var done = false;
303
304                                 // Attach handlers for all browsers
305                                 script.onload = script.onreadystatechange = function() {
306                                         if ( !done && (!this.readyState ||
307                                                         this.readyState === "loaded" || this.readyState === "complete") ) {
308                                                 done = true;
309                                                 success();
310                                                 complete();
311
312                                                 // Handle memory leak in IE
313                                                 script.onload = script.onreadystatechange = null;
314                                                 if ( head && script.parentNode ) {
315                                                         head.removeChild( script );
316                                                 }
317                                         }
318                                 };
319                         }
320
321                         // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
322                         // This arises when a base node is used (#2709 and #4378).
323                         head.insertBefore( script, head.firstChild );
324
325                         // We handle everything using the script element injection
326                         return undefined;
327                 }
328
329                 var requestDone = false;
330
331                 // Create the request object
332                 var xhr = s.xhr();
333
334                 if ( !xhr ) {
335                         return;
336                 }
337
338                 // Open the socket
339                 // Passing null username, generates a login popup on Opera (#2865)
340                 if ( s.username ) {
341                         xhr.open(type, s.url, s.async, s.username, s.password);
342                 } else {
343                         xhr.open(type, s.url, s.async);
344                 }
345
346                 // Need an extra try/catch for cross domain requests in Firefox 3
347                 try {
348                         // Set the correct header, if data is being sent
349                         if ( s.data || origSettings && origSettings.contentType ) {
350                                 xhr.setRequestHeader("Content-Type", s.contentType);
351                         }
352
353                         // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
354                         if ( s.ifModified ) {
355                                 if ( jQuery.lastModified[s.url] ) {
356                                         xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
357                                 }
358
359                                 if ( jQuery.etag[s.url] ) {
360                                         xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
361                                 }
362                         }
363
364                         // Set header so the called script knows that it's an XMLHttpRequest
365                         // Only send the header if it's not a remote XHR
366                         if ( !remote ) {
367                                 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
368                         }
369
370                         // Set the Accepts header for the server, depending on the dataType
371                         xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
372                                 s.accepts[ s.dataType ] + ", */*" :
373                                 s.accepts._default );
374                 } catch(e) {}
375
376                 // Allow custom headers/mimetypes and early abort
377                 if ( s.beforeSend && s.beforeSend.call(callbackContext, xhr, s) === false ) {
378                         // Handle the global AJAX counter
379                         if ( s.global && ! --jQuery.active ) {
380                                 jQuery.event.trigger( "ajaxStop" );
381                         }
382
383                         // close opended socket
384                         xhr.abort();
385                         return false;
386                 }
387
388                 if ( s.global ) {
389                         trigger("ajaxSend", [xhr, s]);
390                 }
391
392                 // Wait for a response to come back
393                 var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
394                         // The request was aborted
395                         if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
396                                 // Opera doesn't call onreadystatechange before this point
397                                 // so we simulate the call
398                                 if ( !requestDone ) {
399                                         complete();
400                                 }
401
402                                 requestDone = true;
403                                 if ( xhr ) {
404                                         xhr.onreadystatechange = jQuery.noop;
405                                 }
406
407                         // The transfer is complete and the data is available, or the request timed out
408                         } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
409                                 requestDone = true;
410                                 xhr.onreadystatechange = jQuery.noop;
411
412                                 status = isTimeout === "timeout" ?
413                                         "timeout" :
414                                         !jQuery.httpSuccess( xhr ) ?
415                                                 "error" :
416                                                 s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
417                                                         "notmodified" :
418                                                         "success";
419
420                                 var errMsg;
421
422                                 if ( status === "success" ) {
423                                         // Watch for, and catch, XML document parse errors
424                                         try {
425                                                 // process the data (runs the xml through httpData regardless of callback)
426                                                 data = jQuery.httpData( xhr, s.dataType, s );
427                                         } catch(err) {
428                                                 status = "parsererror";
429                                                 errMsg = err;
430                                         }
431                                 }
432
433                                 // Make sure that the request was successful or notmodified
434                                 if ( status === "success" || status === "notmodified" ) {
435                                         // JSONP handles its own success callback
436                                         if ( !jsonp ) {
437                                                 success();
438                                         }
439                                 } else {
440                                         jQuery.handleError(s, xhr, status, errMsg);
441                                 }
442
443                                 // Fire the complete handlers
444                                 complete();
445
446                                 if ( isTimeout === "timeout" ) {
447                                         xhr.abort();
448                                 }
449
450                                 // Stop memory leaks
451                                 if ( s.async ) {
452                                         xhr = null;
453                                 }
454                         }
455                 };
456
457                 // Override the abort handler, if we can (IE doesn't allow it, but that's OK)
458                 // Opera doesn't fire onreadystatechange at all on abort
459                 try {
460                         var oldAbort = xhr.abort;
461                         xhr.abort = function() {
462                                 if ( xhr ) {
463                                         oldAbort.call( xhr );
464                                 }
465
466                                 onreadystatechange( "abort" );
467                         };
468                 } catch(e) { }
469
470                 // Timeout checker
471                 if ( s.async && s.timeout > 0 ) {
472                         setTimeout(function() {
473                                 // Check to see if the request is still happening
474                                 if ( xhr && !requestDone ) {
475                                         onreadystatechange( "timeout" );
476                                 }
477                         }, s.timeout);
478                 }
479
480                 // Send the data
481                 try {
482                         xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null );
483                 } catch(e) {
484                         jQuery.handleError(s, xhr, null, e);
485                         // Fire the complete handlers
486                         complete();
487                 }
488
489                 // firefox 1.5 doesn't fire statechange for sync requests
490                 if ( !s.async ) {
491                         onreadystatechange();
492                 }
493
494                 function success() {
495                         // If a local callback was specified, fire it and pass it the data
496                         if ( s.success ) {
497                                 s.success.call( callbackContext, data, status, xhr );
498                         }
499
500                         // Fire the global callback
501                         if ( s.global ) {
502                                 trigger( "ajaxSuccess", [xhr, s] );
503                         }
504                 }
505
506                 function complete() {
507                         // Process result
508                         if ( s.complete ) {
509                                 s.complete.call( callbackContext, xhr, status);
510                         }
511
512                         // The request was completed
513                         if ( s.global ) {
514                                 trigger( "ajaxComplete", [xhr, s] );
515                         }
516
517                         // Handle the global AJAX counter
518                         if ( s.global && ! --jQuery.active ) {
519                                 jQuery.event.trigger( "ajaxStop" );
520                         }
521                 }
522                 
523                 function trigger(type, args) {
524                         (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args);
525                 }
526
527                 // return XMLHttpRequest to allow aborting the request etc.
528                 return xhr;
529         },
530
531         handleError: function( s, xhr, status, e ) {
532                 // If a local callback was specified, fire it
533                 if ( s.error ) {
534                         s.error.call( s.context || s, xhr, status, e );
535                 }
536
537                 // Fire the global callback
538                 if ( s.global ) {
539                         (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
540                 }
541         },
542
543         // Counter for holding the number of active queries
544         active: 0,
545
546         // Determines if an XMLHttpRequest was successful or not
547         httpSuccess: function( xhr ) {
548                 try {
549                         // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
550                         return !xhr.status && location.protocol === "file:" ||
551                                 // Opera returns 0 when status is 304
552                                 ( xhr.status >= 200 && xhr.status < 300 ) ||
553                                 xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
554                 } catch(e) {}
555
556                 return false;
557         },
558
559         // Determines if an XMLHttpRequest returns NotModified
560         httpNotModified: function( xhr, url ) {
561                 var lastModified = xhr.getResponseHeader("Last-Modified"),
562                         etag = xhr.getResponseHeader("Etag");
563
564                 if ( lastModified ) {
565                         jQuery.lastModified[url] = lastModified;
566                 }
567
568                 if ( etag ) {
569                         jQuery.etag[url] = etag;
570                 }
571
572                 // Opera returns 0 when status is 304
573                 return xhr.status === 304 || xhr.status === 0;
574         },
575
576         httpData: function( xhr, type, s ) {
577                 var ct = xhr.getResponseHeader("content-type") || "",
578                         xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
579                         data = xml ? xhr.responseXML : xhr.responseText;
580
581                 if ( xml && data.documentElement.nodeName === "parsererror" ) {
582                         jQuery.error( "parsererror" );
583                 }
584
585                 // Allow a pre-filtering function to sanitize the response
586                 // s is checked to keep backwards compatibility
587                 if ( s && s.dataFilter ) {
588                         data = s.dataFilter( data, type );
589                 }
590
591                 // The filter can actually parse the response
592                 if ( typeof data === "string" ) {
593                         // Get the JavaScript object, if JSON is used.
594                         if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
595                                 data = jQuery.parseJSON( data );
596
597                         // If the type is "script", eval it in global context
598                         } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
599                                 jQuery.globalEval( data );
600                         }
601                 }
602
603                 return data;
604         },
605
606         // Serialize an array of form elements or a set of
607         // key/values into a query string
608         param: function( a, traditional ) {
609                 var s = [];
610                 
611                 // Set traditional to true for jQuery <= 1.3.2 behavior.
612                 if ( traditional === undefined ) {
613                         traditional = jQuery.ajaxSettings.traditional;
614                 }
615                 
616                 // If an array was passed in, assume that it is an array of form elements.
617                 if ( jQuery.isArray(a) || a.jquery ) {
618                         // Serialize the form elements
619                         jQuery.each( a, function() {
620                                 add( this.name, this.value );
621                         });
622                         
623                 } else {
624                         // If traditional, encode the "old" way (the way 1.3.2 or older
625                         // did it), otherwise encode params recursively.
626                         for ( var prefix in a ) {
627                                 buildParams( prefix, a[prefix] );
628                         }
629                 }
630
631                 // Return the resulting serialization
632                 return s.join("&").replace(r20, "+");
633
634                 function buildParams( prefix, obj ) {
635                         if ( jQuery.isArray(obj) ) {
636                                 // Serialize array item.
637                                 jQuery.each( obj, function( i, v ) {
638                                         if ( traditional ) {
639                                                 // Treat each array item as a scalar.
640                                                 add( prefix, v );
641                                         } else {
642                                                 // If array item is non-scalar (array or object), encode its
643                                                 // numeric index to resolve deserialization ambiguity issues.
644                                                 // Note that rack (as of 1.0.0) can't currently deserialize
645                                                 // nested arrays properly, and attempting to do so may cause
646                                                 // a server error. Possible fixes are to modify rack's
647                                                 // deserialization algorithm or to provide an option or flag
648                                                 // to force array serialization to be shallow.
649                                                 buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v );
650                                         }
651                                 });
652                                         
653                         } else if ( !traditional && obj != null && typeof obj === "object" ) {
654                                 // Serialize object item.
655                                 jQuery.each( obj, function( k, v ) {
656                                         buildParams( prefix + "[" + k + "]", v );
657                                 });
658                                         
659                         } else {
660                                 // Serialize scalar item.
661                                 add( prefix, obj );
662                         }
663                 }
664
665                 function add( key, value ) {
666                         // If value is a function, invoke it and return its value
667                         value = jQuery.isFunction(value) ? value() : value;
668                         s[ s.length ] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
669                 }
670         }
671 });