The AJAX plugin is now fully documented, along with some bug fixes and new features.
[jquery.git] / ajax / ajax.js
1 // AJAX Plugin
2 // Docs Here:
3 // http://jquery.com/docs/ajax/
4
5 /**
6  * Load HTML from a remote file and inject it into the DOM
7  */
8 $.fn.load = function( url, params, callback ) {
9         // I overwrote the event plugin's .load
10         // this won't happen again, I hope -John
11         if ( url && url.constructor == Function )
12                 return this.bind("load", url);
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 ( params.constructor == Function ) {
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 = $.param( params );
28                         type = "POST";
29                 }
30         }
31         
32         var self = this;
33         
34         // Request the remote document
35         $.ajax( type, url, params,function(res){
36                         
37                 // Inject the HTML into all the matched elements
38                 self.html(res.responseText).each(function(){
39                         // If a callback function was provided
40                         if ( callback && callback.constructor == Function )
41                                 // Execute it within the context of the element
42                                 $.apply( self, callback, [res.responseText] );
43                 });
44                 
45                 // Execute all the scripts inside of the newly-injected HTML
46                 $("script", self).each(function(){
47                         eval( this.text || this.textContent || this.innerHTML || "");
48                 });
49
50         });
51         
52         return this;
53 };
54
55 /**
56  * Load a remote page using a GET request
57  */
58 $.get = function( url, callback, type ) {
59         // Build and start the HTTP Request
60         $.ajax( "GET", url, null, function(r) {
61                 if ( callback ) callback( $.httpData(r,type) );
62         });
63 };
64
65 /**
66  * Load a remote page using a POST request.
67  */
68 $.post = function( url, data, callback, type ) {
69         // Build and start the HTTP Request
70         $.ajax( "POST", url, $.param(data), function(r) {
71                 if ( callback ) callback( $.httpData(r,type) );
72         });
73 };
74
75 // If IE is used, create a wrapper for the XMLHttpRequest object
76 if ( $.browser == "msie" )
77         XMLHttpRequest = function(){
78                 return new ActiveXObject(
79                         (navigator.userAgent.toLowerCase().indexOf('msie 5') >= 0) ?
80                         "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
81                 );
82         };
83
84 // Counter for holding the number of active queries
85 $.xmlActive = 0;
86
87 // Attach a bunch of functions for handling common AJAX events
88 (function(){
89         var e = ['ajaxStart','ajaxComplete','ajaxError','ajaxSuccess'];
90         
91         for ( var i = 0; i < e.length; i++ ){ (function(){
92                 var o = e[i];
93                 $.fn[o] = function(f){return this.bind(o, f);};
94         })();}
95 })();
96
97 /**
98  * A common wrapper for making XMLHttpRequests
99  */
100 $.ajax = function( type, url, data, ret ) {
101         // If only a single argument was passed in,
102         // assume that it is a object of key/value pairs
103         if ( !url ) {
104                 ret = type.complete;
105                 var success = type.success;
106                 var error = type.error;
107                 data = type.data;
108                 url = type.url;
109                 type = type.type;
110         }
111
112         // Create the request object
113         var xml = new XMLHttpRequest();
114
115         // Open the socket
116         xml.open(type || "GET", url, true);
117         
118         // Set the correct header, if data is being sent
119         if ( data )
120                 xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
121
122         // Set header so calling script knows that it's an XMLHttpRequest
123         xml.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
124
125         // Make sure the browser sends the right content length
126         if ( xml.overrideMimeType )
127                 xml.setRequestHeader('Connection', 'close');
128
129         // Wait for a response to come back
130         xml.onreadystatechange = function(){
131                 // Socket is openend
132                 if ( xml.readyState == 1 ) {
133                         // Increase counter
134                         $.xmlActive++;
135
136                         // Show loader if needed
137                         if ( $.xmlActive >= 1 && $.xmlCreate )
138                                 $.event.trigger( 'ajaxStart' );
139                 }
140
141                 // Socket is closed and data is available
142                 if ( xml.readyState == 4 ) {
143                         // Decrease counter
144                         $.xmlActive--;
145
146                         // Hide loader if needed
147                         if ( $.xmlActive <= 0 && $.xmlDestroy ) {
148                                 $.event.trigger( 'ajaxComplete' );
149                                 $.xmlActive = 0
150                         }
151
152                         // Make sure that the request was successful
153                         if ( $.httpSuccess( xml ) ) {
154                         
155                                 // If a local callback was specified, fire it
156                                 if ( success ) success( xml );
157                                 
158                                 // Fire the global callback
159                                 $.event.trigger( 'ajaxSuccess' );
160                         
161                         // Otherwise, the request was not successful
162                         } else {
163                                 // If a local callback was specified, fire it
164                                 if ( error ) error( xml );
165                                 
166                                 // Fire the global callback
167                                 $.event.trigger( 'ajaxError' );
168                         }
169
170                         // Process result
171                         if ( ret ) ret(xml);
172                 }
173         };
174
175         // Send the data
176         xml.send(data);
177 };
178
179 // Determines if an XMLHttpRequest was successful or not
180 $.httpSuccess = function(r) {
181         return ( r.status && ( r.status >= 200 && r.status < 300 ) || 
182                 r.status == 304 ) || !r.status && location.protocol == 'file:';
183 };
184
185 // Get the data out of an XMLHttpRequest
186 $.httpData = function(r,type) {
187         // Check the headers, or watch for a force override
188         return r.getResponseHeader("content-type").indexOf("xml") > 0 || 
189                 type == "xml" ? r.responseXML : r.responseText;
190 };
191
192 // Serialize an array of form elements or a set of
193 // key/values into a query string
194 $.param = function(a) {
195         var s = [];
196         
197         // If an array was passed in, assume that it is an array
198         // of form elements
199         if ( a.constructor == Array )
200                 // Serialize the form elements
201                 for ( var i = 0; i < a.length; i++ )
202                         s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
203                 
204         // Otherwise, assume that it's an object of key/value pairs
205         else
206                 // Serialize the key/values
207                 for ( var j in a )
208                         s.push( j + "=" + encodeURIComponent( a[j] ) );
209         
210         // Return the resulting serialization
211         return s.join("&");
212 };