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