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