4 * Load HTML from a remote file and inject it into the DOM, only if it's
5 * been modified by the server.
7 * @example $("#feeds").loadIfModified("feeds.html");
8 * @before <div id="feeds"></div>
9 * @result <div id="feeds"><b>45</b> feeds found.</div>
11 * @name loadIfModified
13 * @param String url The URL of the HTML file to load.
14 * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
15 * @param Function callback (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).
18 loadIfModified: function( url, params, callback ) {
19 this.load( url, params, callback, 1 );
23 * Load HTML from a remote file and inject it into the DOM.
25 * @example $("#feeds").load("feeds.html");
26 * @before <div id="feeds"></div>
27 * @result <div id="feeds"><b>45</b> feeds found.</div>
29 * @example $("#feeds").load("feeds.html",
31 * function() { alert("The last 25 entries in the feed have been loaded"); }
33 * @desc Same as above, but with an additional parameter
34 * and a callback that is executed when the data was loaded.
38 * @param String url The URL of the HTML file to load.
39 * @param Object params (optional) A set of key/value pairs that will be sent as data to the server.
40 * @param Function callback (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).
43 load: function( url, params, callback, ifModified ) {
44 if ( url.constructor == Function )
45 return this.bind("load", url);
47 callback = callback || function(){};
49 // Default to a GET request
52 // If the second parameter was provided
55 if ( params.constructor == Function ) {
56 // We assume that it's the callback
60 // Otherwise, build a param string
62 params = jQuery.param( params );
69 // Request the remote document
74 ifModified: ifModified,
75 complete: function(res, status){
76 if ( status == "success" || !ifModified && status == "notmodified" ) {
77 // Inject the HTML into all the matched elements
78 self.html(res.responseText)
79 // Execute all the scripts inside of the newly-injected HTML
82 .each( callback, [res.responseText, status, res] );
84 callback.apply( self, [res.responseText, status, res] );
91 * Serializes a set of input elements into a string of data.
92 * This will serialize all given elements.
94 * A serialization similar to the form submit of a browser is
95 * provided by the form plugin. It also takes multiple-selects
96 * into account, while this method recognizes only a single option.
98 * @example $("input[@type=text]").serialize();
99 * @before <input type='text' name='name' value='John'/>
100 * <input type='text' name='location' value='Boston'/>
101 * @after name=John&location=Boston
102 * @desc Serialize a selection of input elements to a string
108 serialize: function() {
109 return jQuery.param( this );
113 * Evaluate all script tags inside this jQuery. If they have a src attribute,
114 * the script is loaded, otherwise it's content is evaluated.
121 evalScripts: function() {
122 return this.find('script').each(function(){
124 jQuery.getScript( this.src );
126 jQuery.globalEval( this.text || this.textContent || this.innerHTML || "" );
133 // If IE is used, create a wrapper for the XMLHttpRequest object
134 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
135 XMLHttpRequest = function(){
136 return new ActiveXObject("Microsoft.XMLHTTP");
139 // Attach a bunch of functions for handling common AJAX events
142 * Attach a function to be executed whenever an AJAX request begins
143 * and there is none already active.
145 * @example $("#loading").ajaxStart(function(){
148 * @desc Show a loading message whenever an AJAX request starts
149 * (and none is already active).
153 * @param Function callback The function to execute.
158 * Attach a function to be executed whenever all AJAX requests have ended.
160 * @example $("#loading").ajaxStop(function(){
163 * @desc Hide a loading message after all the AJAX requests have stopped.
167 * @param Function callback The function to execute.
172 * Attach a function to be executed whenever an AJAX request completes.
174 * The XMLHttpRequest and settings used for that request are passed
175 * as arguments to the callback.
177 * @example $("#msg").ajaxComplete(function(request, settings){
178 * $(this).append("<li>Request Complete.</li>");
180 * @desc Show a message when an AJAX request completes.
184 * @param Function callback The function to execute.
189 * Attach a function to be executed whenever an AJAX request completes
192 * The XMLHttpRequest and settings used for that request are passed
193 * as arguments to the callback.
195 * @example $("#msg").ajaxSuccess(function(request, settings){
196 * $(this).append("<li>Successful Request!</li>");
198 * @desc Show a message when an AJAX request completes successfully.
202 * @param Function callback The function to execute.
207 * Attach a function to be executed whenever an AJAX request fails.
209 * The XMLHttpRequest and settings used for that request are passed
210 * as arguments to the callback.
212 * @example $("#msg").ajaxError(function(request, settings){
213 * $(this).append("<li>Error requesting page " + settings.url + "</li>");
215 * @desc Show a message when an AJAX request fails.
219 * @param Function callback The function to execute.
224 * Attach a function to be executed before an AJAX request is send.
226 * The XMLHttpRequest and settings used for that request are passed
227 * as arguments to the callback.
229 * @example $("#msg").ajaxSend(function(request, settings){
230 * $(this).append("<li>Starting request at " + settings.url + "</li>");
232 * @desc Show a message before an AJAX request is send.
236 * @param Function callback The function to execute.
241 var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(",");
243 for ( var i = 0; i < e.length; i++ ) new function(){
245 jQuery.fn[o] = function(f){
246 return this.bind(o, f);
254 * Load a remote page using an HTTP GET request.
256 * @example $.get("test.cgi");
258 * @example $.get("test.cgi", { name: "John", time: "2pm" } );
260 * @example $.get("test.cgi", function(data){
261 * alert("Data Loaded: " + data);
264 * @example $.get("test.cgi",
265 * { name: "John", time: "2pm" },
267 * alert("Data Loaded: " + data);
272 * @type XMLHttpRequest
273 * @param String url The URL of the page to load.
274 * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
275 * @param Function callback (optional) A function to be executed whenever the data is loaded.
278 get: function( url, data, callback, type, ifModified ) {
279 // shift arguments if data argument was ommited
280 if ( data && data.constructor == Function ) {
289 ifModified: ifModified
294 * Load a remote page using an HTTP GET request, only if it hasn't
295 * been modified since it was last retrieved.
297 * @example $.getIfModified("test.html");
299 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } );
301 * @example $.getIfModified("test.cgi", function(data){
302 * alert("Data Loaded: " + data);
305 * @example $.getifModified("test.cgi",
306 * { name: "John", time: "2pm" },
308 * alert("Data Loaded: " + data);
312 * @name $.getIfModified
313 * @type XMLHttpRequest
314 * @param String url The URL of the page to load.
315 * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
316 * @param Function callback (optional) A function to be executed whenever the data is loaded.
319 getIfModified: function( url, data, callback, type ) {
320 return jQuery.get(url, data, callback, type, 1);
324 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
326 * Warning: Safari <= 2.0.x is unable to evalulate scripts in a global
327 * context synchronously. If you load functions via getScript, make sure
328 * to call them after a delay.
330 * @example $.getScript("test.js");
332 * @example $.getScript("test.js", function(){
333 * alert("Script loaded and executed.");
337 * @type XMLHttpRequest
338 * @param String url The URL of the page to load.
339 * @param Function callback (optional) A function to be executed whenever the data is loaded.
342 getScript: function( url, callback ) {
343 return jQuery.get(url, null, callback, "script");
347 * Load JSON data using an HTTP GET request.
349 * @example $.getJSON("test.js", function(json){
350 * alert("JSON Data: " + json.users[3].name);
353 * @example $.getJSON("test.js",
354 * { name: "John", time: "2pm" },
356 * alert("JSON Data: " + json.users[3].name);
361 * @type XMLHttpRequest
362 * @param String url The URL of the page to load.
363 * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
364 * @param Function callback A function to be executed whenever the data is loaded.
367 getJSON: function( url, data, callback ) {
368 return jQuery.get(url, data, callback, "json");
372 * Load a remote page using an HTTP POST request.
374 * @example $.post("test.cgi");
376 * @example $.post("test.cgi", { name: "John", time: "2pm" } );
378 * @example $.post("test.cgi", function(data){
379 * alert("Data Loaded: " + data);
382 * @example $.post("test.cgi",
383 * { name: "John", time: "2pm" },
385 * alert("Data Loaded: " + data);
390 * @type XMLHttpRequest
391 * @param String url The URL of the page to load.
392 * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
393 * @param Function callback (optional) A function to be executed whenever the data is loaded.
396 post: function( url, data, callback, type ) {
410 * Set the timeout of all AJAX requests to a specific amount of time.
411 * This will make all future AJAX requests timeout after a specified amount
414 * Set to null or 0 to disable timeouts (default).
416 * You can manually abort requests with the XMLHttpRequest's (returned by
417 * all ajax functions) abort() method.
419 * @example $.ajaxTimeout( 5000 );
420 * @desc Make all AJAX requests timeout after 5 seconds.
422 * @name $.ajaxTimeout
424 * @param Number time How long before an AJAX request times out.
427 ajaxTimeout: function(timeout) {
428 jQuery.timeout = timeout;
431 // Last-Modified header cache for next request
435 * Load a remote page using an HTTP request.
437 * This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for
438 * higher-level abstractions.
440 * $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't
441 * need that object to manipulate directly, but it is available if you need to
442 * abort the request manually.
444 * Note: Make sure the server sends the right mimetype (eg. xml as
445 * "text/xml"). Sending the wrong mimetype will get you into serious
446 * trouble that jQuery can't solve.
448 * Supported datatypes are (see dataType option):
450 * "xml": Returns a XML document that can be processed via jQuery.
452 * "html": Returns HTML as plain text, included script tags are evaluated.
454 * "script": Evaluates the response as Javascript and returns it as plain text.
456 * "json": Evaluates the response as JSON and returns a Javascript Object
458 * $.ajax() takes one argument, an object of key/value pairs, that are
459 * used to initalize and handle the request. These are all the key/values that can
462 * (String) url - The URL to request.
464 * (String) type - The type of request to make ("POST" or "GET"), default is "GET".
466 * (String) dataType - The type of data that you're expecting back from
467 * the server. No default: If the server sends xml, the responseXML, otherwise
468 * the responseText is passed to the success callback.
470 * (Boolean) ifModified - Allow the request to be successful only if the
471 * response has changed since the last request. This is done by checking the
472 * Last-Modified header. Default value is false, ignoring the header.
474 * (Number) timeout - Local timeout to override global timeout, eg. to give a
475 * single request a longer timeout while all others timeout after 1 seconds.
476 * See $.ajaxTimeout() for global timeouts.
478 * (Boolean) global - Wheather to trigger global AJAX event handlers for
479 * this request, default is true. Set to false to prevent that global handlers
480 * like ajaxStart or ajaxStop are triggered.
482 * (Function) error - A function to be called if the request fails. The
483 * function gets passed two arguments: The XMLHttpRequest object and a
484 * string describing the type of error that occurred.
486 * (Function) success - A function to be called if the request succeeds. The
487 * function gets passed one argument: The data returned from the server,
488 * formatted according to the 'dataType' parameter.
490 * (Function) complete - A function to be called when the request finishes. The
491 * function gets passed two arguments: The XMLHttpRequest object and a
492 * string describing the type of success of the request.
494 * (Object|String) data - Data to be sent to the server. Converted to a query
495 * string, if not already a string. Is appended to the url for GET-requests.
496 * See processData option to prevent this automatic processing.
498 * (String) contentType - When sending data to the server, use this content-type.
499 * Default is "application/x-www-form-urlencoded", which is fine for most cases.
501 * (Boolean) processData - By default, data passed in to the data option as an object
502 * other as string will be processed and transformed into a query string, fitting to
503 * the default content-type "application/x-www-form-urlencoded". If you want to send
504 * DOMDocuments, set this option to false.
506 * (Boolean) async - By default, all requests are send asynchronous (set to true).
507 * If you need synchronous requests, set this option to false.
509 * (Function) beforeSend - A pre-callback to set custom headers etc., the
510 * XMLHttpRequest is passed as the only argument.
517 * @desc Load and execute a JavaScript file.
522 * data: "name=John&location=Boston",
523 * success: function(msg){
524 * alert( "Data Saved: " + msg );
527 * @desc Save some data to the server and notify the user once its complete.
529 * @example var html = $.ajax({
533 * @desc Loads data synchronously. Blocks the browser while the requests is active.
534 * It is better to block user interaction with others means when synchronization is
535 * necessary, instead to block the complete browser.
537 * @example var xmlDocument = [create xml document];
540 * processData: false,
542 * success: handleResponse
544 * @desc Sends an xml document as data to the server. By setting the processData
545 * option to false, the automatic conversion of data to strings is prevented.
548 * @type XMLHttpRequest
549 * @param Hash prop A set of properties to initialize the request with.
552 ajax: function( s ) {
553 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
558 timeout: jQuery.timeout,
565 contentType: "application/x-www-form-urlencoded",
573 // convert data if not already a string
574 if (s.processData && typeof s.data != 'string')
575 s.data = jQuery.param(s.data);
576 // append data to url for get requests
577 if( s.type.toLowerCase() == "get" )
578 // "?" + data or "&" + data (in case there are already params)
579 s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data;
582 // Watch for a new set of requests
583 if ( s.global && ! jQuery.active++ )
584 jQuery.event.trigger( "ajaxStart" );
586 var requestDone = false;
588 // Create the request object
589 var xml = new XMLHttpRequest();
592 xml.open(s.type, s.url, s.async);
594 // Set the correct header, if data is being sent
596 xml.setRequestHeader("Content-Type", s.contentType);
598 // Set the If-Modified-Since header, if ifModified mode.
600 xml.setRequestHeader("If-Modified-Since",
601 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
603 // Set header so the called script knows that it's an XMLHttpRequest
604 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
606 // Make sure the browser sends the right content length
607 if ( xml.overrideMimeType )
608 xml.setRequestHeader("Connection", "close");
610 // Allow custom headers/mimetypes
614 jQuery.event.trigger("ajaxSend", [xml, s]);
616 // Wait for a response to come back
617 var onreadystatechange = function(isTimeout){
618 // The transfer is complete and the data is available, or the request timed out
619 if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
622 var status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
623 s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
625 // Make sure that the request was successful or notmodified
626 if ( status != "error" ) {
627 // Cache Last-Modified header, if ifModified mode.
630 modRes = xml.getResponseHeader("Last-Modified");
631 } catch(e) {} // swallow exception thrown by FF if header is not available
633 if ( s.ifModified && modRes )
634 jQuery.lastModified[s.url] = modRes;
636 // process the data (runs the xml through httpData regardless of callback)
637 var data = jQuery.httpData( xml, s.dataType );
639 // If a local callback was specified, fire it and pass it the data
641 s.success( data, status );
643 // Fire the global callback
645 jQuery.event.trigger( "ajaxSuccess", [xml, s] );
647 // Otherwise, the request was not successful
649 // If a local callback was specified, fire it
650 if ( s.error ) s.error( xml, status );
652 // Fire the global callback
654 jQuery.event.trigger( "ajaxError", [xml, s] );
657 // The request was completed
659 jQuery.event.trigger( "ajaxComplete", [xml, s] );
661 // Handle the global AJAX counter
662 if ( s.global && ! --jQuery.active )
663 jQuery.event.trigger( "ajaxStop" );
666 if ( s.complete ) s.complete(xml, status);
669 xml.onreadystatechange = function(){};
673 xml.onreadystatechange = onreadystatechange;
677 setTimeout(function(){
678 // Check to see if the request is still happening
680 // Cancel the request
683 if ( !requestDone ) onreadystatechange( "timeout" );
690 // save non-leaking reference
696 // return XMLHttpRequest to allow aborting the request etc.
700 // Counter for holding the number of active queries
703 // Determines if an XMLHttpRequest was successful or not
704 httpSuccess: function(r) {
706 return !r.status && location.protocol == "file:" ||
707 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
708 jQuery.browser.safari && r.status == undefined;
713 // Determines if an XMLHttpRequest returns NotModified
714 httpNotModified: function(xml, url) {
716 var xmlRes = xml.getResponseHeader("Last-Modified");
718 // Firefox always returns 200. check Last-Modified date
719 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
720 jQuery.browser.safari && xml.status == undefined;
725 /* Get the data out of an XMLHttpRequest.
726 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
727 * otherwise return plain text.
728 * (String) data - The type of data that you're expecting back,
729 * (e.g. "xml", "html", "script")
731 httpData: function(r,type) {
732 var ct = r.getResponseHeader("content-type");
733 var data = !type && ct && ct.indexOf("xml") >= 0;
734 data = type == "xml" || data ? r.responseXML : r.responseText;
736 // If the type is "script", eval it in global context
737 if ( type == "script" ) {
738 jQuery.globalEval( data );
741 // Get the JavaScript object, if JSON is used.
742 if ( type == "json" ) eval( "data = " + data );
744 // evaluate scripts within html
745 if ( type == "html" ) jQuery("<div>").html(data).evalScripts();
750 // Serialize an array of form elements or a set of
751 // key/values into a query string
755 // If an array was passed in, assume that it is an array
757 if ( a.constructor == Array || a.jquery ) {
758 // Serialize the form elements
759 for ( var i = 0; i < a.length; i++ )
760 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
762 // Otherwise, assume that it's an object of key/value pairs
764 // Serialize the key/values
766 // If the value is an array then the key names need to be repeated
767 if( a[j].constructor == Array ) {
768 for (var k = 0; k < a[j].length; k++) {
769 s.push( j + "=" + encodeURIComponent( a[j][k] ) );
772 s.push( j + "=" + encodeURIComponent( a[j] ) );
777 // Return the resulting serialization
781 // evalulates a script in global context
782 // not reliable for safari
783 globalEval: function(data) {
784 if (window.execScript)
785 window.execScript( data );
786 else if(jQuery.browser.safari)
787 // safari doesn't provide a synchronous global eval
788 window.setTimeout( data, 0 );
790 eval.call( window, data );