3 // http://jquery.com/docs/ajax/
6 * Load HTML from a remote file and inject it into the DOM, only if it's
7 * been modified by the server.
9 * @example $("#feeds").loadIfModified("feeds.html")
10 * @before <div id="feeds"></div>
11 * @result <div id="feeds"><b>45</b> feeds found.</div>
13 * @name loadIfModified
15 * @param String url The URL of the HTML file to load.
16 * @param Hash params A set of key/value pairs that will be sent to the server.
17 * @param Function callback A function to be executed whenever the data is loaded.
20 jQuery.fn.loadIfModified = function( url, params, callback ) {
21 this.load( url, params, callback, 1 );
25 * Load HTML from a remote file and inject it into the DOM.
27 * @example $("#feeds").load("feeds.html")
28 * @before <div id="feeds"></div>
29 * @result <div id="feeds"><b>45</b> feeds found.</div>
33 * @param String url The URL of the HTML file to load.
34 * @param Hash params A set of key/value pairs that will be sent to the server.
35 * @param Function callback A function to be executed whenever the data is loaded.
38 jQuery.fn.load = function( url, params, callback, ifModified ) {
39 if ( url.constructor == Function )
40 return this.bind("load", url);
42 callback = callback || function(){};
44 // Default to a GET request
47 // If the second parameter was provided
50 if ( params.constructor == Function ) {
51 // We assume that it's the callback
55 // Otherwise, build a param string
57 params = jQuery.param( params );
64 // Request the remote document
65 jQuery.ajax( type, url, params,function(res, status){
67 if ( status == "success" || !ifModified && status == "notmodified" ) {
68 // Inject the HTML into all the matched elements
69 self.html(res.responseText).each( callback, [res.responseText, status] );
71 // Execute all the scripts inside of the newly-injected HTML
72 $("script", self).each(function(){
74 $.getScript( this.src );
76 eval.call( window, this.text || this.textContent || this.innerHTML || "" );
79 callback.apply( self, [res.responseText, status] );
87 * A function for serializing a set of input elements into
90 * @example $("input[@type=text]").serialize();
91 * @before <input type='text' name='name' value='John'/>
92 * <input type='text' name='location' value='Boston'/>
93 * @after name=John&location=Boston
94 * @desc Serialize a selection of input elements to a string
100 jQuery.fn.serialize = function(){
101 return $.param( this );
104 // If IE is used, create a wrapper for the XMLHttpRequest object
105 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
106 XMLHttpRequest = function(){
107 return new ActiveXObject(
108 navigator.userAgent.indexOf("MSIE 5") >= 0 ?
109 "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
113 // Attach a bunch of functions for handling common AJAX events
116 * Attach a function to be executed whenever an AJAX request begins.
118 * @example $("#loading").ajaxStart(function(){
121 * @desc Show a loading message whenever an AJAX request starts.
125 * @param Function callback The function to execute.
130 * Attach a function to be executed whenever all AJAX requests have ended.
132 * @example $("#loading").ajaxStop(function(){
135 * @desc Hide a loading message after all the AJAX requests have stopped.
139 * @param Function callback The function to execute.
144 * Attach a function to be executed whenever an AJAX request completes.
146 * @example $("#msg").ajaxComplete(function(){
147 * $(this).append("<li>Request Complete.</li>");
149 * @desc Show a message when an AJAX request completes.
153 * @param Function callback The function to execute.
158 * Attach a function to be executed whenever an AJAX request completes
161 * @example $("#msg").ajaxSuccess(function(){
162 * $(this).append("<li>Successful Request!</li>");
164 * @desc Show a message when an AJAX request completes successfully.
168 * @param Function callback The function to execute.
173 * Attach a function to be executed whenever an AJAX request fails.
175 * @example $("#msg").ajaxError(function(){
176 * $(this).append("<li>Error requesting page.</li>");
178 * @desc Show a message when an AJAX request fails.
182 * @param Function callback The function to execute.
187 var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(",");
189 for ( var i = 0; i < e.length; i++ ) new function(){
191 jQuery.fn[o] = function(f){
192 return this.bind(o, f);
200 * Load a remote page using an HTTP GET request. All of the arguments to
201 * the method (except URL) are optional.
203 * @example $.get("test.cgi")
205 * @example $.get("test.cgi", { name: "John", time: "2pm" } )
207 * @example $.get("test.cgi", function(data){
208 * alert("Data Loaded: " + data);
211 * @example $.get("test.cgi",
212 * { name: "John", time: "2pm" },
214 * alert("Data Loaded: " + data);
220 * @param String url The URL of the page to load.
221 * @param Hash params A set of key/value pairs that will be sent to the server.
222 * @param Function callback A function to be executed whenever the data is loaded.
225 get: function( url, data, callback, type, ifModified ) {
226 if ( data.constructor == Function ) {
232 if ( data ) url += "?" + jQuery.param(data);
234 // Build and start the HTTP Request
235 jQuery.ajax( "GET", url, null, function(r, status) {
236 if ( callback ) callback( jQuery.httpData(r,type), status );
241 * Load a remote page using an HTTP GET request, only if it hasn't
242 * been modified since it was last retrieved. All of the arguments to
243 * the method (except URL) are optional.
245 * @example $.getIfModified("test.html")
247 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } )
249 * @example $.getIfModified("test.cgi", function(data){
250 * alert("Data Loaded: " + data);
253 * @example $.getifModified("test.cgi",
254 * { name: "John", time: "2pm" },
256 * alert("Data Loaded: " + data);
260 * @name $.getIfModified
262 * @param String url The URL of the page to load.
263 * @param Hash params A set of key/value pairs that will be sent to the server.
264 * @param Function callback A function to be executed whenever the data is loaded.
267 getIfModified: function( url, data, callback, type ) {
268 jQuery.get(url, data, callback, type, 1);
272 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
273 * All of the arguments to the method (except URL) are optional.
275 * @example $.getScript("test.js")
277 * @example $.getScript("test.js", function(){
278 * alert("Script loaded and executed.");
284 * @param String url The URL of the page to load.
285 * @param Function callback A function to be executed whenever the data is loaded.
288 getScript: function( url, data, callback ) {
289 jQuery.get(url, data, callback, "script");
293 * Load a remote JSON object using an HTTP GET request.
294 * All of the arguments to the method (except URL) are optional.
296 * @example $.getJSON("test.js", function(json){
297 * alert("JSON Data: " + json.users[3].name);
300 * @example $.getJSON("test.js",
301 * { name: "John", time: "2pm" },
303 * alert("JSON Data: " + json.users[3].name);
309 * @param String url The URL of the page to load.
310 * @param Hash params A set of key/value pairs that will be sent to the server.
311 * @param Function callback A function to be executed whenever the data is loaded.
314 getJSON: function( url, data, callback ) {
315 jQuery.get(url, data, callback, "json");
319 * Load a remote page using an HTTP POST request. All of the arguments to
320 * the method (except URL) are optional.
322 * @example $.post("test.cgi")
324 * @example $.post("test.cgi", { name: "John", time: "2pm" } )
326 * @example $.post("test.cgi", function(data){
327 * alert("Data Loaded: " + data);
330 * @example $.post("test.cgi",
331 * { name: "John", time: "2pm" },
333 * alert("Data Loaded: " + data);
339 * @param String url The URL of the page to load.
340 * @param Hash params A set of key/value pairs that will be sent to the server.
341 * @param Function callback A function to be executed whenever the data is loaded.
344 post: function( url, data, callback, type ) {
345 // Build and start the HTTP Request
346 jQuery.ajax( "POST", url, jQuery.param(data), function(r, status) {
347 if ( callback ) callback( jQuery.httpData(r,type), status );
355 * Set the timeout of all AJAX requests to a specific amount of time.
356 * This will make all future AJAX requests timeout after a specified amount
357 * of time (the default is no timeout).
359 * @example $.ajaxTimeout( 5000 );
360 * @desc Make all AJAX requests timeout after 5 seconds.
362 * @name $.ajaxTimeout
364 * @param Number time How long before an AJAX request times out.
367 ajaxTimeout: function(timeout) {
368 jQuery.timeout = timeout;
371 // Last-Modified header cache for next request
375 * Load a remote page using an HTTP request. This function is the primary
376 * means of making AJAX requests using jQuery. $.ajax() takes one property,
377 * an object of key/value pairs, that're are used to initalize the request.
379 * These are all the key/values that can be passed in to 'prop':
381 * (String) type - The type of request to make (e.g. "POST" or "GET").
383 * (String) url - The URL of the page to request.
385 * (String) data - A string of data to be sent to the server (POST only).
387 * (String) dataType - The type of data that you're expecting back from
388 * the server (e.g. "xml", "html", "script", or "json").
390 * (Function) error - A function to be called if the request fails. The
391 * function gets passed two arguments: The XMLHttpRequest object and a
392 * string describing the type of error that occurred.
394 * (Function) success - A function to be called if the request succeeds. The
395 * function gets passed one argument: The data returned from the server,
396 * formatted according to the 'dataType' parameter.
398 * (Function) complete - A function to be called when the request finishes. The
399 * function gets passed two arguments: The XMLHttpRequest object and a
400 * string describing the type the success of the request.
407 * @desc Load and execute a JavaScript file.
412 * data: "name=John&location=Boston",
413 * success: function(msg){
414 * alert( "Data Saved: " + msg );
417 * @desc Save some data to the server and notify the user once its complete.
421 * @param Hash prop A set of properties to initialize the request with.
424 ajax: function( type, url, data, ret, ifModified ) {
425 // If only a single argument was passed in,
426 // assume that it is a object of key/value pairs
429 var success = type.success;
430 var error = type.error;
431 var dataType = type.dataType;
437 // Watch for a new set of requests
438 if ( ! jQuery.active++ )
439 jQuery.event.trigger( "ajaxStart" );
441 var requestDone = false;
443 // Create the request object
444 var xml = new XMLHttpRequest();
447 xml.open(type || "GET", url, true);
449 // Set the correct header, if data is being sent
451 xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
453 // Set the If-Modified-Since header, if ifModified mode.
455 xml.setRequestHeader("If-Modified-Since",
456 jQuery.lastModified[url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
458 // Set header so calling script knows that it's an XMLHttpRequest
459 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
461 // Make sure the browser sends the right content length
462 if ( xml.overrideMimeType )
463 xml.setRequestHeader("Connection", "close");
465 // Wait for a response to come back
466 var onreadystatechange = function(istimeout){
467 // The transfer is complete and the data is available, or the request timed out
468 if ( xml && (xml.readyState == 4 || istimeout == "timeout") ) {
471 var status = jQuery.httpSuccess( xml ) && istimeout != "timeout" ?
472 ifModified && jQuery.httpNotModified( xml, url ) ? "notmodified" : "success" : "error";
474 // Make sure that the request was successful or notmodified
475 if ( status != "error" ) {
476 // Cache Last-Modified header, if ifModified mode.
477 var modRes = xml.getResponseHeader("Last-Modified");
478 if ( ifModified && modRes ) jQuery.lastModified[url] = modRes;
480 // If a local callback was specified, fire it
482 success( jQuery.httpData( xml, dataType ), status );
484 // Fire the global callback
485 jQuery.event.trigger( "ajaxSuccess" );
487 // Otherwise, the request was not successful
489 // If a local callback was specified, fire it
490 if ( error ) error( xml, status );
492 // Fire the global callback
493 jQuery.event.trigger( "ajaxError" );
496 // The request was completed
497 jQuery.event.trigger( "ajaxComplete" );
499 // Handle the global AJAX counter
500 if ( ! --jQuery.active )
501 jQuery.event.trigger( "ajaxStop" );
504 if ( ret ) ret(xml, status);
507 xml.onreadystatechange = function(){};
512 xml.onreadystatechange = onreadystatechange;
515 if(jQuery.timeout > 0)
516 setTimeout(function(){
517 // Check to see if the request is still happening
519 // Cancel the request
522 if ( !requestDone ) onreadystatechange( "timeout" );
533 // Counter for holding the number of active queries
536 // Determines if an XMLHttpRequest was successful or not
537 httpSuccess: function(r) {
539 return !r.status && location.protocol == "file:" ||
540 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
541 jQuery.browser.safari && r.status == undefined;
547 // Determines if an XMLHttpRequest returns NotModified
548 httpNotModified: function(xml, url) {
550 var xmlRes = xml.getResponseHeader("Last-Modified");
552 // Firefox always returns 200. check Last-Modified date
553 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
554 jQuery.browser.safari && xml.status == undefined;
560 /* Get the data out of an XMLHttpRequest.
561 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
562 * otherwise return plain text.
563 * (String) data - The type of data that you're expecting back,
564 * (e.g. "xml", "html", "script")
566 httpData: function(r,type) {
567 var ct = r.getResponseHeader("content-type");
568 var data = !type && ct && ct.indexOf("xml") >= 0;
569 data = type == "xml" || data ? r.responseXML : r.responseText;
571 // If the type is "script", eval it
572 if ( type == "script" ) eval.call( window, data );
574 // Get the JavaScript object, if JSON is used.
575 if ( type == "json" ) eval( "data = " + data );
580 // Serialize an array of form elements or a set of
581 // key/values into a query string
585 // If an array was passed in, assume that it is an array
587 if ( a.constructor == Array || a.jquery ) {
588 // Serialize the form elements
589 for ( var i = 0; i < a.length; i++ )
590 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
592 // Otherwise, assume that it's an object of key/value pairs
594 // Serialize the key/values
596 s.push( j + "=" + encodeURIComponent( a[j] ) );
599 // Return the resulting serialization