Added tests, fixed getScript and getJSON, fixed comment in $.ajax
[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          * @test stop();
37          * $('#first').load("data/name.php", function() {
38          *      ok( $('#first').text() == 'ERROR', 'Check if content was injected into the DOM' );
39          *      start();
40          * });
41          *
42          * @name load
43          * @type jQuery
44          * @param String url The URL of the HTML file to load.
45          * @param Hash params A set of key/value pairs that will be sent to the server.
46          * @param Function callback A function to be executed whenever the data is loaded.
47          * @cat AJAX
48          */
49         load: function( url, params, callback, ifModified ) {
50                 if ( url.constructor == Function )
51                         return this.bind("load", url);
52         
53                 callback = callback || function(){};
54         
55                 // Default to a GET request
56                 var type = "GET";
57         
58                 // If the second parameter was provided
59                 if ( params ) {
60                         // If it's a function
61                         if ( params.constructor == Function ) {
62                                 // We assume that it's the callback
63                                 callback = params;
64                                 params = null;
65                                 
66                         // Otherwise, build a param string
67                         } else {
68                                 params = jQuery.param( params );
69                                 type = "POST";
70                         }
71                 }
72                 
73                 var self = this;
74                 
75                 // Request the remote document
76                 jQuery.ajax( type, url, params,function(res, status){
77                         
78                         if ( status == "success" || !ifModified && status == "notmodified" ) {
79                                 // Inject the HTML into all the matched elements
80                                 self.html(res.responseText).each( callback, [res.responseText, status] );
81                                 
82                                 // Execute all the scripts inside of the newly-injected HTML
83                                 $("script", self).each(function(){
84                                         if ( this.src )
85                                                 $.getScript( this.src );
86                                         else
87                                                 eval.call( window, this.text || this.textContent || this.innerHTML || "" );
88                                 });
89                         } else
90                                 callback.apply( self, [res.responseText, status] );
91         
92                 }, ifModified);
93                 
94                 return this;
95         },
96
97         /**
98          * A function for serializing a set of input elements into
99          * a string of data.
100          *
101          * @example $("input[@type=text]").serialize();
102          * @before <input type='text' name='name' value='John'/>
103          * <input type='text' name='location' value='Boston'/>
104          * @after name=John&location=Boston
105          * @desc Serialize a selection of input elements to a string
106          *
107          * @test var data = $(':input').serialize();
108          * ok( data == 'action=Test&text2=Test&radio1=on&radio2=on&check=on&=on&hidden=&foo[bar]=&name=name&button=&=foobar&select1=&select2=3&select3=1', 'Check form serialization as query string' );
109          *
110          * @name serialize
111          * @type String
112          * @cat AJAX
113          */
114         serialize: function() {
115                 return $.param( this );
116         }
117         
118 });
119
120 // If IE is used, create a wrapper for the XMLHttpRequest object
121 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
122         XMLHttpRequest = function(){
123                 return new ActiveXObject(
124                         navigator.userAgent.indexOf("MSIE 5") >= 0 ?
125                         "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
126                 );
127         };
128
129 // Attach a bunch of functions for handling common AJAX events
130
131 /**
132  * Attach a function to be executed whenever an AJAX request begins.
133  *
134  * @example $("#loading").ajaxStart(function(){
135  *   $(this).show();
136  * });
137  * @desc Show a loading message whenever an AJAX request starts.
138  *
139  * @name ajaxStart
140  * @type jQuery
141  * @param Function callback The function to execute.
142  * @cat AJAX
143  */
144  
145 /**
146  * Attach a function to be executed whenever all AJAX requests have ended.
147  *
148  * @example $("#loading").ajaxStop(function(){
149  *   $(this).hide();
150  * });
151  * @desc Hide a loading message after all the AJAX requests have stopped.
152  *
153  * @name ajaxStop
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 an AJAX request completes.
161  *
162  * @example $("#msg").ajaxComplete(function(){
163  *   $(this).append("<li>Request Complete.</li>");
164  * });
165  * @desc Show a message when an AJAX request completes.
166  *
167  * @name ajaxComplete
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  * successfully.
176  *
177  * @example $("#msg").ajaxSuccess(function(){
178  *   $(this).append("<li>Successful Request!</li>");
179  * });
180  * @desc Show a message when an AJAX request completes successfully.
181  *
182  * @name ajaxSuccess
183  * @type jQuery
184  * @param Function callback The function to execute.
185  * @cat AJAX
186  */
187  
188 /**
189  * Attach a function to be executed whenever an AJAX request fails.
190  *
191  * @example $("#msg").ajaxError(function(){
192  *   $(this).append("<li>Error requesting page.</li>");
193  * });
194  * @desc Show a message when an AJAX request fails.
195  *
196  * @name ajaxError
197  * @type jQuery
198  * @param Function callback The function to execute.
199  * @cat AJAX
200  */
201
202 new function(){
203         var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(",");
204         
205         for ( var i = 0; i < e.length; i++ ) new function(){
206                 var o = e[i];
207                 jQuery.fn[o] = function(f){
208                         return this.bind(o, f);
209                 };
210         };
211 };
212
213 jQuery.extend({
214
215         /**
216          * Load a remote page using an HTTP GET request. All of the arguments to
217          * the method (except URL) are optional.
218          *
219          * @example $.get("test.cgi")
220          *
221          * @example $.get("test.cgi", { name: "John", time: "2pm" } )
222          *
223          * @example $.get("test.cgi", function(data){
224          *   alert("Data Loaded: " + data);
225          * })
226          *
227          * @example $.get("test.cgi",
228          *   { name: "John", time: "2pm" },
229          *   function(data){
230          *     alert("Data Loaded: " + data);
231          *   }
232          * )
233          *
234          * @test stop();
235          * $.get("data/dashboard.xml", function(xml) {
236          *     var content = [];
237      *     $('tab', xml).each(function(k) {
238      *         // workaround for IE needed here, $(this).text() throws an error
239      *         // content[k] = $.trim(this.firstChild.data) || $(this).text();
240      *         content[k] = $(this).text();
241      *     });
242          *         ok( content[0] && content[0].match(/blabla/), 'Check first tab' );
243          *     ok( content[1] && content[1].match(/blublu/), 'Check second tab' );
244          *     start();
245          * });
246          *
247          * @name $.get
248          * @type jQuery
249          * @param String url The URL of the page to load.
250          * @param Hash params A set of key/value pairs that will be sent to the server.
251          * @param Function callback A function to be executed whenever the data is loaded.
252          * @cat AJAX
253          */
254         get: function( url, data, callback, type, ifModified ) {
255                 if ( data.constructor == Function ) {
256                         type = callback;
257                         callback = data;
258                         data = null;
259                 }
260                 
261                 if ( data ) url += "?" + jQuery.param(data);
262                 
263                 // Build and start the HTTP Request
264                 jQuery.ajax( "GET", url, null, function(r, status) {
265                         if ( callback ) callback( jQuery.httpData(r,type), status );
266                 }, ifModified);
267         },
268         
269         /**
270          * Load a remote page using an HTTP GET request, only if it hasn't
271          * been modified since it was last retrieved. All of the arguments to
272          * the method (except URL) are optional.
273          *
274          * @example $.getIfModified("test.html")
275          *
276          * @example $.getIfModified("test.html", { name: "John", time: "2pm" } )
277          *
278          * @example $.getIfModified("test.cgi", function(data){
279          *   alert("Data Loaded: " + data);
280          * })
281          *
282          * @example $.getifModified("test.cgi",
283          *   { name: "John", time: "2pm" },
284          *   function(data){
285          *     alert("Data Loaded: " + data);
286          *   }
287          * )
288          *
289          * @name $.getIfModified
290          * @type jQuery
291          * @param String url The URL of the page to load.
292          * @param Hash params A set of key/value pairs that will be sent to the server.
293          * @param Function callback A function to be executed whenever the data is loaded.
294          * @cat AJAX
295          */
296         getIfModified: function( url, data, callback, type ) {
297                 jQuery.get(url, data, callback, type, 1);
298         },
299
300         /**
301          * Loads, and executes, a remote JavaScript file using an HTTP GET request.
302          * All of the arguments to the method (except URL) are optional.
303          *
304          * @example $.getScript("test.js")
305          *
306          * @example $.getScript("test.js", function(){
307          *   alert("Script loaded and executed.");
308          * })
309          *
310          * @test stop();
311          * $.getScript("data/test.js", function() {
312          *      ok( foobar == "bar", 'Check if script was evaluated' );
313          *      start();
314          * });
315          *
316          * @name $.getScript
317          * @type jQuery
318          * @param String url The URL of the page to load.
319          * @param Function callback A function to be executed whenever the data is loaded.
320          * @cat AJAX
321          */
322         getScript: function( url, callback ) {
323                 jQuery.get(url, callback, "script");
324         },
325         
326         /**
327          * Load a remote JSON object using an HTTP GET request.
328          * All of the arguments to the method (except URL) are optional.
329          *
330          * @example $.getJSON("test.js", function(json){
331          *   alert("JSON Data: " + json.users[3].name);
332          * })
333          *
334          * @example $.getJSON("test.js",
335          *   { name: "John", time: "2pm" },
336          *   function(json){
337          *     alert("JSON Data: " + json.users[3].name);
338          *   }
339          * )
340          *
341          * @test stop();
342          * $.getJSON("data/json.php", {json: "array"}, function(json) {
343          *   ok( json[0].name == 'John', 'Check JSON: first, name' );
344          *   ok( json[0].age == 21, 'Check JSON: first, age' );
345          *   ok( json[1].name == 'Peter', 'Check JSON: second, name' );
346          *   ok( json[1].age == 25, 'Check JSON: second, age' );
347          *   start();
348          * });
349          * @test stop();
350          * $.getJSON("data/json.php", function(json) {
351          *   ok( json.data.lang == 'en', 'Check JSON: lang' );
352          *   ok( json.data.length == 25, 'Check JSON: length' );
353          *   start();
354          * });
355          *
356          * @name $.getJSON
357          * @type jQuery
358          * @param String url The URL of the page to load.
359          * @param Hash params A set of key/value pairs that will be sent to the server.
360          * @param Function callback A function to be executed whenever the data is loaded.
361          * @cat AJAX
362          */
363         getJSON: function( url, data, callback ) {
364                 if(callback)
365                         jQuery.get(url, data, callback, "json");
366                 else {
367                         jQuery.get(url, data, "json");
368                 }
369         },
370         
371         /**
372          * Load a remote page using an HTTP POST request. All of the arguments to
373          * the method (except URL) are optional.
374          *
375          * @example $.post("test.cgi")
376          *
377          * @example $.post("test.cgi", { name: "John", time: "2pm" } )
378          *
379          * @example $.post("test.cgi", function(data){
380          *   alert("Data Loaded: " + data);
381          * })
382          *
383          * @example $.post("test.cgi",
384          *   { name: "John", time: "2pm" },
385          *   function(data){
386          *     alert("Data Loaded: " + data);
387          *   }
388          * )
389          *
390          * @test stop();
391          * $.post("data/name.php", {xml: "5-2"}, function(xml){
392          *   $('math', xml).each(function() {
393          *          ok( $('calculation', this).text() == '5-2', 'Check for XML' );
394          *          ok( $('result', this).text() == '3', 'Check for XML' );
395          *       });
396          *   start();
397          * });
398          *
399          * @name $.post
400          * @type jQuery
401          * @param String url The URL of the page to load.
402          * @param Hash params A set of key/value pairs that will be sent to the server.
403          * @param Function callback A function to be executed whenever the data is loaded.
404          * @cat AJAX
405          */
406         post: function( url, data, callback, type ) {
407                 // Build and start the HTTP Request
408                 jQuery.ajax( "POST", url, jQuery.param(data), function(r, status) {
409                         if ( callback ) callback( jQuery.httpData(r,type), status );
410                 });
411         },
412         
413         // timeout (ms)
414         timeout: 0,
415
416         /**
417          * Set the timeout of all AJAX requests to a specific amount of time.
418          * This will make all future AJAX requests timeout after a specified amount
419          * of time (the default is no timeout).
420          *
421          * @example $.ajaxTimeout( 5000 );
422          * @desc Make all AJAX requests timeout after 5 seconds.
423          *
424          * @test stop();
425          * var passed = 0;
426          * var timeout;
427          * $.ajaxTimeout(1000);
428          * var pass = function() {
429          *      passed++;
430          *      if(passed == 2) {
431          *              ok( true, 'Check local and global callbacks after timeout' );
432          *              clearTimeout(timeout);
433          *              start();
434          *      }
435          * };
436          * var fail = function(ba) {
437          *      console.debug(ba);
438          *      ok( false, 'Check for timeout failed' );
439          *      start();
440          * };
441          * timeout = setTimeout(fail, 1500);
442          * $('#main').ajaxError(pass);
443          * $.ajax({
444          *   type: "GET",
445          *   url: "data/name.php?wait=5",
446          *   error: pass,
447          *   success: fail
448          * });
449          *
450          * @name $.ajaxTimeout
451          * @type jQuery
452          * @param Number time How long before an AJAX request times out.
453          * @cat AJAX
454          */
455         ajaxTimeout: function(timeout) {
456                 jQuery.timeout = timeout;
457         },
458
459         // Last-Modified header cache for next request
460         lastModified: {},
461         
462         /**
463          * Load a remote page using an HTTP request. This function is the primary
464          * means of making AJAX requests using jQuery. $.ajax() takes one property,
465          * an object of key/value pairs, that're are used to initalize the request.
466          *
467          * These are all the key/values that can be passed in to 'prop':
468          *
469          * (String) type - The type of request to make (e.g. "POST" or "GET").
470          *
471          * (String) url - The URL of the page to request.
472          * 
473          * (String) data - A string of data to be sent to the server (POST only).
474          *
475          * (String) dataType - The type of data that you're expecting back from
476          * the server (e.g. "xml", "html", "script", or "json").
477          *
478          * (Function) error - A function to be called if the request fails. The
479          * function gets passed two arguments: The XMLHttpRequest object and a
480          * string describing the type of error that occurred.
481          *
482          * (Function) success - A function to be called if the request succeeds. The
483          * function gets passed one argument: The data returned from the server,
484          * formatted according to the 'dataType' parameter.
485          *
486          * (Function) complete - A function to be called when the request finishes. The
487          * function gets passed two arguments: The XMLHttpRequest object and a
488          * string describing the type the success of the request.
489          *
490          * @example $.ajax({
491          *   type: "GET",
492          *   url: "test.js",
493          *   dataType: "script"
494          * })
495          * @desc Load and execute a JavaScript file.
496          *
497          * @example $.ajax({
498          *   type: "POST",
499          *   url: "some.php",
500          *   data: "name=John&location=Boston",
501          *   success: function(msg){
502          *     alert( "Data Saved: " + msg );
503          *   }
504          * });
505          * @desc Save some data to the server and notify the user once its complete.
506          *
507          * @test stop();
508          * $.ajax({
509          *   type: "GET",
510          *   url: "data/name.php?name=foo",
511          *   success: function(msg){
512          *     ok( msg == 'bar', 'Check for GET' );
513          *     start();
514          *   }
515          * });
516          *
517          * @test stop();
518          * $.ajax({
519          *   type: "POST",
520          *   url: "data/name.php",
521          *   data: "name=peter",
522          *   success: function(msg){
523          *     ok( msg == 'pan', 'Check for POST' );
524          *     start();
525          *   }
526          * });
527          *
528          * @name $.ajax
529          * @type jQuery
530          * @param Hash prop A set of properties to initialize the request with.
531          * @cat AJAX
532          */
533         ajax: function( type, url, data, ret, ifModified ) {
534                 // If only a single argument was passed in,
535                 // assume that it is a object of key/value pairs
536                 if ( !url ) {
537                         ret = type.complete;
538                         var success = type.success;
539                         var error = type.error;
540                         var dataType = type.dataType;
541                         data = type.data;
542                         url = type.url;
543                         type = type.type;
544                 }
545                 
546                 // Watch for a new set of requests
547                 if ( ! jQuery.active++ )
548                         jQuery.event.trigger( "ajaxStart" );
549
550                 var requestDone = false;
551         
552                 // Create the request object
553                 var xml = new XMLHttpRequest();
554         
555                 // Open the socket
556                 xml.open(type || "GET", url, true);
557                 
558                 // Set the correct header, if data is being sent
559                 if ( data )
560                         xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
561                 
562                 // Set the If-Modified-Since header, if ifModified mode.
563                 if ( ifModified )
564                         xml.setRequestHeader("If-Modified-Since",
565                                 jQuery.lastModified[url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
566                 
567                 // Set header so the called script knows that it's an XMLHttpRequest
568                 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
569         
570                 // Make sure the browser sends the right content length
571                 if ( xml.overrideMimeType )
572                         xml.setRequestHeader("Connection", "close");
573                 
574                 // Wait for a response to come back
575                 var onreadystatechange = function(istimeout){
576                         // The transfer is complete and the data is available, or the request timed out
577                         if ( xml && (xml.readyState == 4 || istimeout == "timeout") ) {
578                                 requestDone = true;
579
580                                 var status = jQuery.httpSuccess( xml ) && istimeout != "timeout" ?
581                                         ifModified && jQuery.httpNotModified( xml, url ) ? "notmodified" : "success" : "error";
582                                 
583                                 // Make sure that the request was successful or notmodified
584                                 if ( status != "error" ) {
585                                         // Cache Last-Modified header, if ifModified mode.
586                                         var modRes = xml.getResponseHeader("Last-Modified");
587                                         if ( ifModified && modRes ) jQuery.lastModified[url] = modRes;
588                                         
589                                         // If a local callback was specified, fire it
590                                         if ( success )
591                                                 success( jQuery.httpData( xml, dataType ), status );
592                                         
593                                         // Fire the global callback
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 ( error ) error( xml, status );
600                                         
601                                         // Fire the global callback
602                                         jQuery.event.trigger( "ajaxError" );
603                                 }
604                                 
605                                 // The request was completed
606                                 jQuery.event.trigger( "ajaxComplete" );
607                                 
608                                 // Handle the global AJAX counter
609                                 if ( ! --jQuery.active )
610                                         jQuery.event.trigger( "ajaxStop" );
611         
612                                 // Process result
613                                 if ( ret ) ret(xml, status);
614                                 
615                                 // Stop memory leaks
616                                 xml.onreadystatechange = function(){};
617                                 xml = null;
618                                 
619                         }
620                 };
621                 xml.onreadystatechange = onreadystatechange;
622                 
623                 // Timeout checker
624                 if(jQuery.timeout > 0)
625                         setTimeout(function(){
626                                 // Check to see if the request is still happening
627                                 if (xml) {
628                                         // Cancel the request
629                                         xml.abort();
630
631                                         if ( !requestDone ) onreadystatechange( "timeout" );
632
633                                         // Clear from memory
634                                         xml = null;
635                                 }
636                         }, jQuery.timeout);
637                 
638                 // Send the data
639                 xml.send(data);
640         },
641         
642         // Counter for holding the number of active queries
643         active: 0,
644         
645         // Determines if an XMLHttpRequest was successful or not
646         httpSuccess: function(r) {
647                 try {
648                         return !r.status && location.protocol == "file:" ||
649                                 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
650                                 jQuery.browser.safari && r.status == undefined;
651                 } catch(e){}
652
653                 return false;
654         },
655
656         // Determines if an XMLHttpRequest returns NotModified
657         httpNotModified: function(xml, url) {
658                 try {
659                         var xmlRes = xml.getResponseHeader("Last-Modified");
660
661                         // Firefox always returns 200. check Last-Modified date
662                         return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
663                                 jQuery.browser.safari && xml.status == undefined;
664                 } catch(e){}
665
666                 return false;
667         },
668         
669         /* Get the data out of an XMLHttpRequest.
670          * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
671          * otherwise return plain text.
672          * (String) data - The type of data that you're expecting back,
673          * (e.g. "xml", "html", "script")
674          */
675         httpData: function(r,type) {
676                 var ct = r.getResponseHeader("content-type");
677                 var data = !type && ct && ct.indexOf("xml") >= 0;
678                 data = type == "xml" || data ? r.responseXML : r.responseText;
679
680                 // If the type is "script", eval it
681                 if ( type == "script" ) eval.call( window, data );
682
683                 // Get the JavaScript object, if JSON is used.
684                 if ( type == "json" ) eval( "data = " + data );
685
686                 return data;
687         },
688         
689         // Serialize an array of form elements or a set of
690         // key/values into a query string
691         param: function(a) {
692                 var s = [];
693                 
694                 // If an array was passed in, assume that it is an array
695                 // of form elements
696                 if ( a.constructor == Array || a.jquery ) {
697                         // Serialize the form elements
698                         for ( var i = 0; i < a.length; i++ )
699                                 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
700                         
701                 // Otherwise, assume that it's an object of key/value pairs
702                 } else {
703                         // Serialize the key/values
704                         for ( var j in a )
705                                 s.push( j + "=" + encodeURIComponent( a[j] ) );
706                 }
707                 
708                 // Return the resulting serialization
709                 return s.join("&");
710         }
711
712 });