Fixed serializing arrays (bug #448)
[jquery.git] / src / ajax / ajax.js
1 jQuery.fn.extend({
2
3         /**
4          * Load HTML from a remote file and inject it into the DOM, only if it's
5          * been modified by the server.
6          *
7          * @example $("#feeds").loadIfModified("feeds.html")
8          * @before <div id="feeds"></div>
9          * @result <div id="feeds"><b>45</b> feeds found.</div>
10          *
11          * @name loadIfModified
12          * @type jQuery
13          * @param String url The URL of the HTML file to load.
14          * @param Hash params A set of key/value pairs that will be sent to the server.
15          * @param Function callback A function to be executed whenever the data is loaded.
16          * @cat AJAX
17          */
18         loadIfModified: function( url, params, callback ) {
19                 this.load( url, params, callback, 1 );
20         },
21
22         /**
23          * Load HTML from a remote file and inject it into the DOM.
24          *
25          * @example $("#feeds").load("feeds.html")
26          * @before <div id="feeds"></div>
27          * @result <div id="feeds"><b>45</b> feeds found.</div>
28          *
29          * @example $("#feeds").load("feeds.html",
30          *   {test: true},
31          *   function() { alert("load is done"); }
32          * );
33          * @desc Same as above, but with an additional parameter
34          * and a callback that is executed when the data was loaded.
35          *
36          * @name load
37          * @type jQuery
38          * @param String url The URL of the HTML file to load.
39          * @param Object params A set of key/value pairs that will be sent as data to the server.
40          * @param Function callback A function to be executed whenever the data is loaded (parameters: responseText, status and reponse itself).
41          * @cat AJAX
42          */
43         load: function( url, params, callback, ifModified ) {
44                 if ( url.constructor == Function )
45                         return this.bind("load", url);
46
47                 callback = callback || function(){};
48
49                 // Default to a GET request
50                 var type = "GET";
51
52                 // If the second parameter was provided
53                 if ( params ) {
54                         // If it's a function
55                         if ( params.constructor == Function ) {
56                                 // We assume that it's the callback
57                                 callback = params;
58                                 params = null;
59
60                         // Otherwise, build a param string
61                         } else {
62                                 params = jQuery.param( params );
63                                 type = "POST";
64                         }
65                 }
66
67                 var self = this;
68
69                 // Request the remote document
70                 jQuery.ajax({
71                         url: url,
72                         type: type,
73                         data: params,
74                         ifModified: ifModified,
75                         complete: function(res, status){
76                                 if ( status == "success" || !ifModified && status == "notmodified" ) {
77                                         // Inject the HTML into all the matched elements
78                                         self.html(res.responseText)
79                                           // Execute all the scripts inside of the newly-injected HTML
80                                           .evalScripts()
81                                           // Execute callback
82                                           .each( callback, [res.responseText, status, res] );
83                                 } else
84                                         callback.apply( self, [res.responseText, status, res] );
85                         }
86                 });
87                 return this;
88         },
89
90         /**
91          * Serializes a set of input elements into a string of data.
92          * This will serialize all given elements. If you need
93          * serialization similar to the form submit of a browser,
94          * you should use the form plugin. This is also true for
95          * selects with multiple attribute set, only a single option
96          * is serialized.
97          *
98          * @example $("input[@type=text]").serialize();
99          * @before <input type='text' name='name' value='John'/>
100          * <input type='text' name='location' value='Boston'/>
101          * @after name=John&location=Boston
102          * @desc Serialize a selection of input elements to a string
103          *
104          * @name serialize
105          * @type String
106          * @cat AJAX
107          */
108         serialize: function() {
109                 return jQuery.param( this );
110         },
111
112         /**
113          * Evaluate all script tags inside this jQuery. If they have a src attribute,
114          * the script is loaded, otherwise it's content is evaluated.
115          *
116          * @name evalScripts
117          * @type jQuery
118          * @private
119          * @cat AJAX
120          */
121         evalScripts: function() {
122                 return this.find('script').each(function(){
123                         if ( this.src )
124                                 // for some weird reason, it doesn't work if the callback is ommited
125                                 jQuery.getScript( this.src );
126                         else {
127                                 jQuery.eval ( this.text || this.textContent || this.innerHTML || "" );
128                         }
129                 }).end();
130         }
131
132 });
133
134 // If IE is used, create a wrapper for the XMLHttpRequest object
135 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
136         XMLHttpRequest = function(){
137                 return new ActiveXObject(
138                         navigator.userAgent.indexOf("MSIE 5") >= 0 ?
139                         "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
140                 );
141         };
142
143 // Attach a bunch of functions for handling common AJAX events
144
145 /**
146  * Attach a function to be executed whenever an AJAX request begins.
147  *
148  * @example $("#loading").ajaxStart(function(){
149  *   $(this).show();
150  * });
151  * @desc Show a loading message whenever an AJAX request starts.
152  *
153  * @name ajaxStart
154  * @type jQuery
155  * @param Function callback The function to execute.
156  * @cat AJAX
157  */
158
159 /**
160  * Attach a function to be executed whenever all AJAX requests have ended.
161  *
162  * @example $("#loading").ajaxStop(function(){
163  *   $(this).hide();
164  * });
165  * @desc Hide a loading message after all the AJAX requests have stopped.
166  *
167  * @name ajaxStop
168  * @type jQuery
169  * @param Function callback The function to execute.
170  * @cat AJAX
171  */
172
173 /**
174  * Attach a function to be executed whenever an AJAX request completes.
175  *
176  * @example $("#msg").ajaxComplete(function(){
177  *   $(this).append("<li>Request Complete.</li>");
178  * });
179  * @desc Show a message when an AJAX request completes.
180  *
181  * @name ajaxComplete
182  * @type jQuery
183  * @param Function callback The function to execute.
184  * @cat AJAX
185  */
186
187 /**
188  * Attach a function to be executed whenever an AJAX request completes
189  * successfully.
190  *
191  * @example $("#msg").ajaxSuccess(function(){
192  *   $(this).append("<li>Successful Request!</li>");
193  * });
194  * @desc Show a message when an AJAX request completes successfully.
195  *
196  * @name ajaxSuccess
197  * @type jQuery
198  * @param Function callback The function to execute.
199  * @cat AJAX
200  */
201
202 /**
203  * Attach a function to be executed whenever an AJAX request fails.
204  *
205  * @example $("#msg").ajaxError(function(){
206  *   $(this).append("<li>Error requesting page.</li>");
207  * });
208  * @desc Show a message when an AJAX request fails.
209  *
210  * @name ajaxError
211  * @type jQuery
212  * @param Function callback The function to execute.
213  * @cat AJAX
214  */
215
216 new function(){
217         var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(",");
218
219         for ( var i = 0; i < e.length; i++ ) new function(){
220                 var o = e[i];
221                 jQuery.fn[o] = function(f){
222                         return this.bind(o, f);
223                 };
224         };
225 };
226
227 jQuery.extend({
228
229         /**
230          * Load a remote page using an HTTP GET request. All of the arguments to
231          * the method (except URL) are optional.
232          *
233          * @example $.get("test.cgi")
234          *
235          * @example $.get("test.cgi", { name: "John", time: "2pm" } )
236          *
237          * @example $.get("test.cgi", function(data){
238          *   alert("Data Loaded: " + data);
239          * })
240          *
241          * @example $.get("test.cgi",
242          *   { name: "John", time: "2pm" },
243          *   function(data){
244          *     alert("Data Loaded: " + data);
245          *   }
246          * )
247          *
248          * @name $.get
249          * @type undefined
250          * @param String url The URL of the page to load.
251          * @param Hash params A set of key/value pairs that will be sent to the server.
252          * @param Function callback A function to be executed whenever the data is loaded.
253          * @cat AJAX
254          */
255         get: function( url, data, callback, type, ifModified ) {
256                 // shift arguments if data argument was ommited
257                 if ( data && data.constructor == Function ) {
258                         callback = data;
259                         data = null;
260                 }
261
262                 // Delegate
263                 jQuery.ajax({
264                         url: url,
265                         data: data,
266                         success: callback,
267                         dataType: type,
268                         ifModified: ifModified
269                 });
270         },
271
272         /**
273          * Load a remote page using an HTTP GET request, only if it hasn't
274          * been modified since it was last retrieved. All of the arguments to
275          * the method (except URL) are optional.
276          *
277          * @example $.getIfModified("test.html")
278          *
279          * @example $.getIfModified("test.html", { name: "John", time: "2pm" } )
280          *
281          * @example $.getIfModified("test.cgi", function(data){
282          *   alert("Data Loaded: " + data);
283          * })
284          *
285          * @example $.getifModified("test.cgi",
286          *   { name: "John", time: "2pm" },
287          *   function(data){
288          *     alert("Data Loaded: " + data);
289          *   }
290          * )
291          *
292          * @name $.getIfModified
293          * @type undefined
294          * @param String url The URL of the page to load.
295          * @param Hash params A set of key/value pairs that will be sent to the server.
296          * @param Function callback A function to be executed whenever the data is loaded.
297          * @cat AJAX
298          */
299         getIfModified: function( url, data, callback, type ) {
300                 jQuery.get(url, data, callback, type, 1);
301         },
302
303         /**
304          * Loads, and executes, a remote JavaScript file using an HTTP GET request.
305          * All of the arguments to the method (except URL) are optional.
306          *
307          * @example $.getScript("test.js")
308          *
309          * @example $.getScript("test.js", function(){
310          *   alert("Script loaded and executed.");
311          * })
312          *
313          * @name $.getScript
314          * @type undefined
315          * @param String url The URL of the page to load.
316          * @param Function callback A function to be executed whenever the data is loaded.
317          * @cat AJAX
318          */
319         getScript: function( url, callback ) {
320                 if(callback)
321                         jQuery.get(url, null, callback, "script");
322                 else {
323                         jQuery.get(url, null, null, "script");
324                 }
325         },
326
327         /**
328          * Load a remote JSON object using an HTTP GET request.
329          * All of the arguments to the method (except URL) are optional.
330          *
331          * @example $.getJSON("test.js", function(json){
332          *   alert("JSON Data: " + json.users[3].name);
333          * })
334          *
335          * @example $.getJSON("test.js",
336          *   { name: "John", time: "2pm" },
337          *   function(json){
338          *     alert("JSON Data: " + json.users[3].name);
339          *   }
340          * )
341          *
342          * @name $.getJSON
343          * @type undefined
344          * @param String url The URL of the page to load.
345          * @param Hash params A set of key/value pairs that will be sent to the server.
346          * @param Function callback A function to be executed whenever the data is loaded.
347          * @cat AJAX
348          */
349         getJSON: function( url, data, callback ) {
350                 jQuery.get(url, data, callback, "json");
351         },
352
353         /**
354          * Load a remote page using an HTTP POST request. All of the arguments to
355          * the method (except URL) are optional.
356          *
357          * @example $.post("test.cgi")
358          *
359          * @example $.post("test.cgi", { name: "John", time: "2pm" } )
360          *
361          * @example $.post("test.cgi", function(data){
362          *   alert("Data Loaded: " + data);
363          * })
364          *
365          * @example $.post("test.cgi",
366          *   { name: "John", time: "2pm" },
367          *   function(data){
368          *     alert("Data Loaded: " + data);
369          *   }
370          * )
371          *
372          * @name $.post
373          * @type undefined
374          * @param String url The URL of the page to load.
375          * @param Hash params A set of key/value pairs that will be sent to the server.
376          * @param Function callback A function to be executed whenever the data is loaded.
377          * @cat AJAX
378          */
379         post: function( url, data, callback, type ) {
380                 // Delegate
381                 jQuery.ajax({
382                         type: "POST",
383                         url: url,
384                         data: data,
385                         success: callback,
386                         dataType: type
387                 });
388         },
389
390         // timeout (ms)
391         timeout: 0,
392
393         /**
394          * Set the timeout of all AJAX requests to a specific amount of time.
395          * This will make all future AJAX requests timeout after a specified amount
396          * of time (the default is no timeout).
397          *
398          * @example $.ajaxTimeout( 5000 );
399          * @desc Make all AJAX requests timeout after 5 seconds.
400          *
401          * @name $.ajaxTimeout
402          * @type undefined
403          * @param Number time How long before an AJAX request times out.
404          * @cat AJAX
405          */
406         ajaxTimeout: function(timeout) {
407                 jQuery.timeout = timeout;
408         },
409
410         // Last-Modified header cache for next request
411         lastModified: {},
412
413         /**
414          * Load a remote page using an HTTP request. This function is the primary
415          * means of making AJAX requests using jQuery. 
416          *
417          * $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't
418          * need that object to manipulate directly, but it is available if you need to
419          * abort the request manually.
420          *
421          * Please note: Make sure the server sends the right mimetype (eg. xml as
422          * "text/xml"). Sending the wrong mimetype will get you into serious
423          * trouble that jQuery can't solve.
424          *
425          * Supported datatypes (see dataType option) are:
426          *
427          * "xml": Returns a XML document that can be processed via jQuery.
428          *
429          * "html": Returns HTML as plain text, included script tags are evaluated.
430          *
431          * "script": Evaluates the response as Javascript and returns it as plain text.
432          *
433          * "json": Evaluates the response as JSON and returns a Javascript Object
434          *
435          * $.ajax() takes one property, an object of key/value pairs, that are
436          * used to initalize the request. These are all the key/values that can
437          * be passed in to 'prop':
438          *
439          * (String) url - The URL of the page to request.
440          *
441          * (String) type - The type of request to make (e.g. "POST" or "GET"), default is "GET".
442          *
443          * (String) dataType - The type of data that you're expecting back from
444          * the server. No default: If the server sends xml, the responseXML, otherwise
445          * the responseText is is passed to the success callback.
446          *
447          * (Boolean) ifModified - Allow the request to be successful only if the
448          * response has changed since the last request, default is false, ignoring
449          * the Last-Modified header
450          *
451          * (Number) timeout - Local timeout to override global timeout, eg. to give a
452          * single request a longer timeout while all others timeout after 1 seconds,
453          * see $.ajaxTimeout()
454          *
455          * (Boolean) global - Wheather to trigger global AJAX event handlers for
456          * this request, default is true. Set to false to prevent that global handlers
457          * like ajaxStart or ajaxStop are triggered.
458          *
459          * (Function) error - A function to be called if the request fails. The
460          * function gets passed two arguments: The XMLHttpRequest object and a
461          * string describing the type of error that occurred.
462          *
463          * (Function) success - A function to be called if the request succeeds. The
464          * function gets passed one argument: The data returned from the server,
465          * formatted according to the 'dataType' parameter.
466          *
467          * (Function) complete - A function to be called when the request finishes. The
468          * function gets passed two arguments: The XMLHttpRequest object and a
469          * string describing the type the success of the request.
470          *
471          * (Object|String) data - Data to be sent to the server. Converted to a query
472          * string, if not already a string. Is appended to the url for GET-requests.
473          * Override processData option to prevent processing.
474          *
475          * (String) contentType - When sending data to the server, use this content-type,
476          * default is "application/x-www-form-urlencoded", which is fine for most cases.
477          *
478          * (Boolean) processData - By default, data passed in as an object other as string
479          * will be processed and transformed into a query string, fitting to the default
480          * content-type "application/x-www-form-urlencoded". If you want to send DOMDocuments,
481          * set this option to false.
482          *
483          * (Boolean) async - By default, all requests are send asynchronous (set to true).
484          * If you need synchronous requests, set this option to false.
485          *
486          * @example $.ajax({
487          *   type: "GET",
488          *   url: "test.js",
489          *   dataType: "script"
490          * })
491          * @desc Load and execute a JavaScript file.
492          *
493          * @example $.ajax({
494          *   type: "POST",
495          *   url: "some.php",
496          *   data: "name=John&location=Boston",
497          *   success: function(msg){
498          *     alert( "Data Saved: " + msg );
499          *   }
500          * });
501          * @desc Save some data to the server and notify the user once its complete.
502          *
503          * @name $.ajax
504          * @type XMLHttpRequest
505          * @param Hash prop A set of properties to initialize the request with.
506          * @cat AJAX
507          */
508         ajax: function( s ) {
509                 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
510                 s = jQuery.extend({
511                         global: true,
512                         ifModified: false,
513                         type: "GET",
514                         timeout: jQuery.timeout,
515                         complete: null,
516                         success: null,
517                         error: null,
518                         dataType: null,
519                         url: null,
520                         data: null,
521                         contentType: "application/x-www-form-urlencoded",
522                         processData: true,
523                         async: true
524                 }, s);
525
526                 // if data available
527                 if ( s.data ) {
528                         // convert data if not already a string
529                         if (s.processData && typeof s.data != 'string')
530                         s.data = jQuery.param(s.data);
531                         // append data to url for get requests
532                         if( s.type.toLowerCase() == "get" )
533                                 // "?" + data or "&" + data (in case there are already params)
534                                 s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data;
535                 }
536
537                 // Watch for a new set of requests
538                 if ( s.global && ! jQuery.active++ )
539                         jQuery.event.trigger( "ajaxStart" );
540
541                 var requestDone = false;
542
543                 // Create the request object
544                 var xml = new XMLHttpRequest();
545
546                 // Open the socket
547                 xml.open(s.type, s.url, s.async);
548
549                 // Set the correct header, if data is being sent
550                 if ( s.data )
551                         xml.setRequestHeader("Content-Type", s.contentType);
552
553                 // Set the If-Modified-Since header, if ifModified mode.
554                 if ( s.ifModified )
555                         xml.setRequestHeader("If-Modified-Since",
556                                 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
557
558                 // Set header so the called script knows that it's an XMLHttpRequest
559                 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
560
561                 // Make sure the browser sends the right content length
562                 if ( xml.overrideMimeType )
563                         xml.setRequestHeader("Connection", "close");
564
565                 // Wait for a response to come back
566                 var onreadystatechange = function(isTimeout){
567                         // The transfer is complete and the data is available, or the request timed out
568                         if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
569                                 requestDone = true;
570
571                                 var status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
572                                         s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
573
574                                 // Make sure that the request was successful or notmodified
575                                 if ( status != "error" ) {
576                                         // Cache Last-Modified header, if ifModified mode.
577                                         var modRes;
578                                         try {
579                                                 modRes = xml.getResponseHeader("Last-Modified");
580                                         } catch(e) {} // swallow exception thrown by FF if header is not available
581
582                                         if ( s.ifModified && modRes )
583                                                 jQuery.lastModified[s.url] = modRes;
584
585                                         // process the data (runs the xml through httpData regardless of callback)
586                                         var data = jQuery.httpData( xml, s.dataType );
587
588                                         // If a local callback was specified, fire it and pass it the data
589                                         if ( s.success )
590                                                 s.success( data, status );
591
592                                         // Fire the global callback
593                                         if( s.global )
594                                                 jQuery.event.trigger( "ajaxSuccess" );
595
596                                 // Otherwise, the request was not successful
597                                 } else {
598                                         // If a local callback was specified, fire it
599                                         if ( s.error ) s.error( xml, status );
600
601                                         // Fire the global callback
602                                         if( s.global )
603                                                 jQuery.event.trigger( "ajaxError" );
604                                 }
605
606                                 // The request was completed
607                                 if( s.global )
608                                         jQuery.event.trigger( "ajaxComplete" );
609
610                                 // Handle the global AJAX counter
611                                 if ( s.global && ! --jQuery.active )
612                                         jQuery.event.trigger( "ajaxStop" );
613
614                                 // Process result
615                                 if ( s.complete ) s.complete(xml, status);
616
617                                 // Stop memory leaks
618                                 xml.onreadystatechange = function(){};
619                                 xml = null;
620
621                         }
622                 };
623                 xml.onreadystatechange = onreadystatechange;
624
625                 // Timeout checker
626                 if(s.timeout > 0)
627                         setTimeout(function(){
628                                 // Check to see if the request is still happening
629                                 if (xml) {
630                                         // Cancel the request
631                                         xml.abort();
632
633                                         if ( !requestDone ) onreadystatechange( "timeout" );
634
635                                         // Clear from memory
636                                         xml = null;
637                                 }
638                         }, s.timeout);
639
640                 // Send the data
641                 xml.send(s.data);
642                 
643                 // return XMLHttpRequest to allow aborting the request etc.
644                 return xml;
645         },
646
647         // Counter for holding the number of active queries
648         active: 0,
649
650         // Determines if an XMLHttpRequest was successful or not
651         httpSuccess: function(r) {
652                 try {
653                         return !r.status && location.protocol == "file:" ||
654                                 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
655                                 jQuery.browser.safari && r.status == undefined;
656                 } catch(e){}
657
658                 return false;
659         },
660
661         // Determines if an XMLHttpRequest returns NotModified
662         httpNotModified: function(xml, url) {
663                 try {
664                         var xmlRes = xml.getResponseHeader("Last-Modified");
665
666                         // Firefox always returns 200. check Last-Modified date
667                         return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
668                                 jQuery.browser.safari && xml.status == undefined;
669                 } catch(e){}
670
671                 return false;
672         },
673
674         /* Get the data out of an XMLHttpRequest.
675          * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
676          * otherwise return plain text.
677          * (String) data - The type of data that you're expecting back,
678          * (e.g. "xml", "html", "script")
679          */
680         httpData: function(r,type) {
681                 var ct = r.getResponseHeader("content-type");
682                 var data = !type && ct && ct.indexOf("xml") >= 0;
683                 data = type == "xml" || data ? r.responseXML : r.responseText;
684
685                 // If the type is "script", eval it in global context
686                 if ( type == "script" ) {
687                         jQuery.eval( data );
688                 }
689
690                 // Get the JavaScript object, if JSON is used.
691                 if ( type == "json" ) eval( "data = " + data );
692
693                 // evaluate scripts within html
694                 if ( type == "html" ) jQuery("<div>").html(data).evalScripts();
695
696                 return data;
697         },
698
699         // Serialize an array of form elements or a set of
700         // key/values into a query string
701         param: function(a) {
702                 var s = [];
703
704                 // If an array was passed in, assume that it is an array
705                 // of form elements
706                 if ( a.constructor == Array || a.jquery ) {
707                         // Serialize the form elements
708                         for ( var i = 0; i < a.length; i++ )
709                                 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
710
711                 // Otherwise, assume that it's an object of key/value pairs
712                 } else {
713                         // Serialize the key/values
714                         for ( var j in a ) {
715                                 // If the value is an array then the key names need to be repeated
716                                 if( a[j].constructor == Array ) {
717                                         for (var k = 0; k < a[j].length; k++) {
718                                                 s.push( j + "=" + encodeURIComponent( a[j][k] ) );
719                                         }
720                                 } else {
721                                         s.push( j + "=" + encodeURIComponent( a[j] ) );
722                                 }
723                         }
724                 }
725
726                 // Return the resulting serialization
727                 return s.join("&");
728         },
729         
730         // TODO document me
731         eval: function(data) {
732                 if (window.execScript)
733                         window.execScript( data );
734                 else
735                         eval.call( window, data );
736         }
737
738 });