Made some changes to the form plugin, to simplify it and bring it up to date.
[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 jQuery.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 = jQuery.param( params );
28                         type = "POST";
29                 }
30         }
31         
32         var self = this;
33         
34         // Request the remote document
35         jQuery.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                                 callback.apply( self, [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 // If IE is used, create a wrapper for the XMLHttpRequest object
56 if ( jQuery.browser.msie )
57         XMLHttpRequest = function(){
58                 return new ActiveXObject(
59                         navigator.userAgent.indexOf("MSIE 5") >= 0 ?
60                         "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
61                 );
62         };
63
64 // Attach a bunch of functions for handling common AJAX events
65 new function(){
66         var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(',');
67         
68         for ( var i = 0; i < e.length; i++ ) new function(){
69                 var o = e[i];
70                 jQuery.fn[o] = function(f){
71                         return this.bind(o, f);
72                 };
73         }
74 };
75
76 jQuery.extend({
77
78         /**
79          * Load a remote page using a GET request
80          */
81         get: function( url, data, callback, type ) {
82                 if ( data.constructor == Function ) {
83                         callback = data;
84                         data = null;
85                 }
86                 
87                 if ( data )
88                         url += "?" + jQuery.param(data);
89                 
90                 // Build and start the HTTP Request
91                 jQuery.ajax( "GET", url, null, function(r) {
92                         if ( callback ) callback( jQuery.httpData(r,type) );
93                 });
94         },
95         
96         /**
97          * Load a remote page using a POST request.
98          */
99         post: function( url, data, callback, type ) {
100                 // Build and start the HTTP Request
101                 jQuery.ajax( "POST", url, jQuery.param(data), function(r) {
102                         if ( callback ) callback( jQuery.httpData(r,type) );
103                 });
104         },
105         
106         /**
107          * A common wrapper for making XMLHttpRequests
108          */
109         ajax: function( type, url, data, ret ) {
110                 // If only a single argument was passed in,
111                 // assume that it is a object of key/value pairs
112                 if ( !url ) {
113                         ret = type.complete;
114                         var success = type.success;
115                         var error = type.error;
116                         data = type.data;
117                         url = type.url;
118                         type = type.type;
119                 }
120                 
121                 // Watch for a new set of requests
122                 if ( ! jQuery.active++ )
123                         jQuery.event.trigger( "ajaxStart" );
124         
125                 // Create the request object
126                 var xml = new XMLHttpRequest();
127         
128                 // Open the socket
129                 xml.open(type || "GET", url, true);
130                 
131                 // Set the correct header, if data is being sent
132                 if ( data )
133                         xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
134         
135                 // Set header so calling script knows that it's an XMLHttpRequest
136                 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
137         
138                 // Make sure the browser sends the right content length
139                 if ( xml.overrideMimeType )
140                         xml.setRequestHeader("Connection", "close");
141         
142                 // Wait for a response to come back
143                 xml.onreadystatechange = function(){
144                         // The transfer is complete and the data is available
145                         if ( xml.readyState == 4 ) {
146                                 // Make sure that the request was successful
147                                 if ( jQuery.httpSuccess( xml ) ) {
148                                 
149                                         // If a local callback was specified, fire it
150                                         if ( success ) success( xml );
151                                         
152                                         // Fire the global callback
153                                         jQuery.event.trigger( "ajaxSuccess" );
154                                 
155                                 // Otherwise, the request was not successful
156                                 } else {
157                                         // If a local callback was specified, fire it
158                                         if ( error ) error( xml );
159                                         
160                                         // Fire the global callback
161                                         jQuery.event.trigger( "ajaxError" );
162                                 }
163                                 
164                                 // The request was completed
165                                 jQuery.event.trigger( "ajaxComplete" );
166                                 
167                                 // Handle the global AJAX counter
168                                 if ( ! --jQuery.active )
169                                         jQuery.event.trigger( "ajaxStop" );
170         
171                                 // Process result
172                                 if ( ret ) ret(xml);
173
174                                 // Stop memory leaks
175                                 xml.onreadystatechange = function(){};
176                                 xml = null;
177                         }
178                 };
179         
180                 // Send the data
181                 xml.send(data);
182         },
183         
184         // Counter for holding the number of active queries
185         active: 0,
186         
187         // Determines if an XMLHttpRequest was successful or not
188         httpSuccess: function(r) {
189                 try {
190                         return r.status ?
191                                 ( r.status >= 200 && r.status < 300 ) || r.status == 304 :
192                                 location.protocol == "file:";
193                 } catch(e){}
194                 return false;
195         },
196         
197         // Get the data out of an XMLHttpRequest.
198         // Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
199         // otherwise return plain text.
200         httpData: function(r,type) {
201                 var ct = r.getResponseHeader("content-type");
202                 var xml = ( !type || type == "xml" ) && ct && ct.indexOf("xml") >= 0;
203                 return xml ? r.responseXML : r.responseText;
204         },
205         
206         // Serialize an array of form elements or a set of
207         // key/values into a query string
208         param: function(a) {
209                 var s = [];
210                 
211                 // If an array was passed in, assume that it is an array
212                 // of form elements
213                 if ( a.constructor == Array )
214                         // Serialize the form elements
215                         for ( var i = 0; i < a.length; i++ )
216                                 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
217                         
218                 // Otherwise, assume that it's an object of key/value pairs
219                 else
220                         // Serialize the key/values
221                         for ( var j in a )
222                                 s.push( j + "=" + encodeURIComponent( a[j] ) );
223                 
224                 // Return the resulting serialization
225                 return s.join("&");
226         }
227
228 });