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 Map params (optional) 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).
19 loadIfModified: function( url, params, callback ) {
20 this.load( url, params, callback, 1 );
24 * Load HTML from a remote file and inject it into the DOM.
26 * Note: Avoid to use this to load scripts, instead use $.getScript.
27 * IE strips script tags when there aren't any other characters in front of it.
29 * @example $("#feeds").load("feeds.html");
30 * @before <div id="feeds"></div>
31 * @result <div id="feeds"><b>45</b> feeds found.</div>
33 * @example $("#feeds").load("feeds.html",
35 * function() { alert("The last 25 entries in the feed have been loaded"); }
37 * @desc Same as above, but with an additional parameter
38 * and a callback that is executed when the data was loaded.
42 * @param String url The URL of the HTML file to load.
43 * @param Object params (optional) A set of key/value pairs that will be sent as data to the server.
44 * @param Function callback (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).
47 load: function( url, params, callback, ifModified ) {
48 if ( jQuery.isFunction( url ) )
49 return this.bind("load", url);
51 callback = callback || function(){};
53 // Default to a GET request
56 // If the second parameter was provided
59 if ( jQuery.isFunction( params ) ) {
60 // We assume that it's the callback
64 // Otherwise, build a param string
66 params = jQuery.param( params );
72 // Request the remote document
77 ifModified: ifModified,
78 complete: function(res, status){
79 // If successful, inject the HTML into all the matched elements
80 if ( status == "success" || !ifModified && status == "notmodified" )
81 self.html(res.responseText);
83 // Add delay to account for Safari's delay in globalEval
84 setTimeout(function(){
85 self.each( callback, [res.responseText, status, res] );
93 * Serializes a set of input elements into a string of data.
94 * This will serialize all given elements.
96 * A serialization similar to the form submit of a browser is
97 * provided by the [http://www.malsup.com/jquery/form/ Form Plugin].
98 * It also takes multiple-selects
99 * into account, while this method recognizes only a single option.
101 * @example $("input[@type=text]").serialize();
102 * @before <input type='text' name='name' value='John'/>
103 * <input type='text' name='location' value='Boston'/>
104 * @after name=John&location=Boston
105 * @desc Serialize a selection of input elements to a string
111 serialize: function() {
112 return jQuery.param( this );
116 // This method no longer does anything - all script evaluation is
117 // taken care of within the HTML injection methods.
118 evalScripts: function(){}
122 // Attach a bunch of functions for handling common AJAX events
125 * Attach a function to be executed whenever an AJAX request begins
126 * and there is none already active.
128 * @example $("#loading").ajaxStart(function(){
131 * @desc Show a loading message whenever an AJAX request starts
132 * (and none is already active).
136 * @param Function callback The function to execute.
141 * Attach a function to be executed whenever all AJAX requests have ended.
143 * @example $("#loading").ajaxStop(function(){
146 * @desc Hide a loading message after all the AJAX requests have stopped.
150 * @param Function callback The function to execute.
155 * Attach a function to be executed whenever an AJAX request completes.
157 * The XMLHttpRequest and settings used for that request are passed
158 * as arguments to the callback.
160 * @example $("#msg").ajaxComplete(function(request, settings){
161 * $(this).append("<li>Request Complete.</li>");
163 * @desc Show a message when an AJAX request completes.
167 * @param Function callback The function to execute.
172 * Attach a function to be executed whenever an AJAX request completes
175 * The XMLHttpRequest and settings used for that request are passed
176 * as arguments to the callback.
178 * @example $("#msg").ajaxSuccess(function(request, settings){
179 * $(this).append("<li>Successful Request!</li>");
181 * @desc Show a message when an AJAX request completes successfully.
185 * @param Function callback The function to execute.
190 * Attach a function to be executed whenever an AJAX request fails.
192 * The XMLHttpRequest and settings used for that request are passed
193 * as arguments to the callback. A third argument, an exception object,
194 * is passed if an exception occured while processing the request.
196 * @example $("#msg").ajaxError(function(request, settings){
197 * $(this).append("<li>Error requesting page " + settings.url + "</li>");
199 * @desc Show a message when an AJAX request fails.
203 * @param Function callback The function to execute.
208 * Attach a function to be executed before an AJAX request is sent.
210 * The XMLHttpRequest and settings used for that request are passed
211 * as arguments to the callback.
213 * @example $("#msg").ajaxSend(function(request, settings){
214 * $(this).append("<li>Starting request at " + settings.url + "</li>");
216 * @desc Show a message before an AJAX request is sent.
220 * @param Function callback The function to execute.
223 jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
224 jQuery.fn[o] = function(f){
225 return this.bind(o, f);
232 * Load a remote page using an HTTP GET request.
234 * This is an easy way to send a simple GET request to a server
235 * without having to use the more complex $.ajax function. It
236 * allows a single callback function to be specified that will
237 * be executed when the request is complete (and only if the response
238 * has a successful response code). If you need to have both error
239 * and success callbacks, you may want to use $.ajax.
241 * @example $.get("test.cgi");
243 * @example $.get("test.cgi", { name: "John", time: "2pm" } );
245 * @example $.get("test.cgi", function(data){
246 * alert("Data Loaded: " + data);
249 * @example $.get("test.cgi",
250 * { name: "John", time: "2pm" },
252 * alert("Data Loaded: " + data);
257 * @type XMLHttpRequest
258 * @param String url The URL of the page to load.
259 * @param Map params (optional) Key/value pairs that will be sent to the server.
260 * @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
263 get: function( url, data, callback, type, ifModified ) {
264 // shift arguments if data argument was ommited
265 if ( jQuery.isFunction( data ) ) {
276 ifModified: ifModified
281 * Load a remote page using an HTTP GET request, only if it hasn't
282 * been modified since it was last retrieved.
284 * @example $.getIfModified("test.html");
286 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } );
288 * @example $.getIfModified("test.cgi", function(data){
289 * alert("Data Loaded: " + data);
292 * @example $.getifModified("test.cgi",
293 * { name: "John", time: "2pm" },
295 * alert("Data Loaded: " + data);
299 * @name $.getIfModified
300 * @type XMLHttpRequest
301 * @param String url The URL of the page to load.
302 * @param Map params (optional) Key/value pairs that will be sent to the server.
303 * @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
307 getIfModified: function( url, data, callback, type ) {
308 return jQuery.get(url, data, callback, type, 1);
312 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
314 * Warning: Safari <= 2.0.x is unable to evaluate scripts in a global
315 * context synchronously. If you load functions via getScript, make sure
316 * to call them after a delay.
318 * @example $.getScript("test.js");
320 * @example $.getScript("test.js", function(){
321 * alert("Script loaded and executed.");
325 * @type XMLHttpRequest
326 * @param String url The URL of the page to load.
327 * @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
330 getScript: function( url, callback ) {
331 return jQuery.get(url, null, callback, "script");
335 * Load JSON data using an HTTP GET request.
337 * @example $.getJSON("test.js", function(json){
338 * alert("JSON Data: " + json.users[3].name);
341 * @example $.getJSON("test.js",
342 * { name: "John", time: "2pm" },
344 * alert("JSON Data: " + json.users[3].name);
349 * @type XMLHttpRequest
350 * @param String url The URL of the page to load.
351 * @param Map params (optional) Key/value pairs that will be sent to the server.
352 * @param Function callback A function to be executed whenever the data is loaded successfully.
355 getJSON: function( url, data, callback ) {
356 return jQuery.get(url, data, callback, "json");
360 * Load a remote page using an HTTP POST request.
362 * @example $.post("test.cgi");
364 * @example $.post("test.cgi", { name: "John", time: "2pm" } );
366 * @example $.post("test.cgi", function(data){
367 * alert("Data Loaded: " + data);
370 * @example $.post("test.cgi",
371 * { name: "John", time: "2pm" },
373 * alert("Data Loaded: " + data);
378 * @type XMLHttpRequest
379 * @param String url The URL of the page to load.
380 * @param Map params (optional) Key/value pairs that will be sent to the server.
381 * @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
384 post: function( url, data, callback, type ) {
385 if ( jQuery.isFunction( data ) ) {
400 * Set the timeout in milliseconds of all AJAX requests to a specific amount of time.
401 * This will make all future AJAX requests timeout after a specified amount
404 * Set to null or 0 to disable timeouts (default).
406 * You can manually abort requests with the XMLHttpRequest's (returned by
407 * all ajax functions) abort() method.
409 * Deprecated. Use $.ajaxSetup instead.
411 * @example $.ajaxTimeout( 5000 );
412 * @desc Make all AJAX requests timeout after 5 seconds.
414 * @name $.ajaxTimeout
416 * @param Number time How long before an AJAX request times out, in milliseconds.
420 ajaxTimeout: function( timeout ) {
421 jQuery.ajaxSettings.timeout = timeout;
425 * Setup global settings for AJAX requests.
427 * See $.ajax for a description of all available options.
429 * @example $.ajaxSetup( {
434 * $.ajax({ data: myData });
435 * @desc Sets the defaults for AJAX requests to the url "/xmlhttp/",
436 * disables global handlers and uses POST instead of GET. The following
437 * AJAX requests then sends some data without having to set anything else.
441 * @param Map settings Key/value pairs to use for all AJAX requests
444 ajaxSetup: function( settings ) {
445 jQuery.extend( jQuery.ajaxSettings, settings );
452 contentType: "application/x-www-form-urlencoded",
458 // Last-Modified header cache for next request
462 * Load a remote page using an HTTP request.
464 * This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for
465 * higher-level abstractions that are often easier to understand and use,
466 * but don't offer as much functionality (such as error callbacks).
468 * $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't
469 * need that object to manipulate directly, but it is available if you need to
470 * abort the request manually.
472 * '''Note:''' If you specify the dataType option described below, make sure
473 * the server sends the correct MIME type in the response (eg. xml as "text/xml").
474 * Sending the wrong MIME type can lead to unexpected problems in your script.
475 * See [[Specifying the Data Type for AJAX Requests]] for more information.
477 * Supported datatypes are (see dataType option):
479 * "xml": Returns a XML document that can be processed via jQuery.
481 * "html": Returns HTML as plain text, included script tags are evaluated.
483 * "script": Evaluates the response as Javascript and returns it as plain text.
485 * "json": Evaluates the response as JSON and returns a Javascript Object
487 * $.ajax() takes one argument, an object of key/value pairs, that are
488 * used to initalize and handle the request. These are all the key/values that can
491 * (String) url - The URL to request.
493 * (String) type - The type of request to make ("POST" or "GET"), default is "GET".
495 * (String) dataType - The type of data that you're expecting back from
496 * the server. No default: If the server sends xml, the responseXML, otherwise
497 * the responseText is passed to the success callback.
499 * (Boolean) ifModified - Allow the request to be successful only if the
500 * response has changed since the last request. This is done by checking the
501 * Last-Modified header. Default value is false, ignoring the header.
503 * (Number) timeout - Local timeout in milliseconds to override global timeout, eg. to give a
504 * single request a longer timeout while all others timeout after 1 second.
505 * See $.ajaxTimeout() for global timeouts.
507 * (Boolean) global - Whether to trigger global AJAX event handlers for
508 * this request, default is true. Set to false to prevent that global handlers
509 * like ajaxStart or ajaxStop are triggered.
511 * (Function) error - A function to be called if the request fails. The
512 * function gets passed tree arguments: The XMLHttpRequest object, a
513 * string describing the type of error that occurred and an optional
514 * exception object, if one occured.
516 * (Function) success - A function to be called if the request succeeds. The
517 * function gets passed one argument: The data returned from the server,
518 * formatted according to the 'dataType' parameter.
520 * (Function) complete - A function to be called when the request finishes. The
521 * function gets passed two arguments: The XMLHttpRequest object and a
522 * string describing the type of success of the request.
524 * (Object|String) data - Data to be sent to the server. Converted to a query
525 * string, if not already a string. Is appended to the url for GET-requests.
526 * See processData option to prevent this automatic processing.
528 * (String) contentType - When sending data to the server, use this content-type.
529 * Default is "application/x-www-form-urlencoded", which is fine for most cases.
531 * (Boolean) processData - By default, data passed in to the data option as an object
532 * other as string will be processed and transformed into a query string, fitting to
533 * the default content-type "application/x-www-form-urlencoded". If you want to send
534 * DOMDocuments, set this option to false.
536 * (Boolean) async - By default, all requests are sent asynchronous (set to true).
537 * If you need synchronous requests, set this option to false.
539 * (Function) beforeSend - A pre-callback to set custom headers etc., the
540 * XMLHttpRequest is passed as the only argument.
547 * @desc Load and execute a JavaScript file.
552 * data: "name=John&location=Boston",
553 * success: function(msg){
554 * alert( "Data Saved: " + msg );
557 * @desc Save some data to the server and notify the user once its complete.
559 * @example var html = $.ajax({
563 * @desc Loads data synchronously. Blocks the browser while the requests is active.
564 * It is better to block user interaction by other means when synchronization is
567 * @example var xmlDocument = [create xml document];
570 * processData: false,
572 * success: handleResponse
574 * @desc Sends an xml document as data to the server. By setting the processData
575 * option to false, the automatic conversion of data to strings is prevented.
578 * @type XMLHttpRequest
579 * @param Map properties Key/value pairs to initialize the request with.
581 * @see ajaxSetup(Map)
583 ajax: function( s ) {
584 // Extend the settings, but re-extend 's' so that it can be
585 // checked again later (in the test suite, specifically)
586 s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
590 // convert data if not already a string
591 if ( s.processData && typeof s.data != "string" )
592 s.data = jQuery.param(s.data);
594 // append data to url for get requests
595 if ( s.type.toLowerCase() == "get" ) {
596 // "?" + data or "&" + data (in case there are already params)
597 s.url += (s.url.indexOf("?") > -1 ? "&" : "?") + s.data;
599 // IE likes to send both get and post data, prevent this
604 // Watch for a new set of requests
605 if ( s.global && ! jQuery.active++ )
606 jQuery.event.trigger( "ajaxStart" );
608 var requestDone = false;
610 // Create the request object; Microsoft failed to properly
611 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
612 var xml = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
615 xml.open(s.type, s.url, s.async);
617 // Set the correct header, if data is being sent
619 xml.setRequestHeader("Content-Type", s.contentType);
621 // Set the If-Modified-Since header, if ifModified mode.
623 xml.setRequestHeader("If-Modified-Since",
624 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
626 // Set header so the called script knows that it's an XMLHttpRequest
627 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
629 // Allow custom headers/mimetypes
634 jQuery.event.trigger("ajaxSend", [xml, s]);
636 // Wait for a response to come back
637 var onreadystatechange = function(isTimeout){
638 // The transfer is complete and the data is available, or the request timed out
639 if ( !requestDone && xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
642 // clear poll interval
648 var status = isTimeout == "timeout" && "timeout" ||
649 !jQuery.httpSuccess( xml ) && "error" ||
650 s.ifModified && jQuery.httpNotModified( xml, s.url ) && "notmodified" ||
653 if ( status == "success" ) {
654 // Watch for, and catch, XML document parse errors
656 // process the data (runs the xml through httpData regardless of callback)
657 var data = jQuery.httpData( xml, s.dataType );
659 status = "parsererror";
663 // Make sure that the request was successful or notmodified
664 if ( status == "success" ) {
665 // Cache Last-Modified header, if ifModified mode.
668 modRes = xml.getResponseHeader("Last-Modified");
669 } catch(e) {} // swallow exception thrown by FF if header is not available
671 if ( s.ifModified && modRes )
672 jQuery.lastModified[s.url] = modRes;
674 // If a local callback was specified, fire it and pass it the data
676 s.success( data, status );
678 // Fire the global callback
680 jQuery.event.trigger( "ajaxSuccess", [xml, s] );
682 jQuery.handleError(s, xml, status);
684 // The request was completed
686 jQuery.event.trigger( "ajaxComplete", [xml, s] );
688 // Handle the global AJAX counter
689 if ( s.global && ! --jQuery.active )
690 jQuery.event.trigger( "ajaxStop" );
694 s.complete(xml, status);
703 // don't attach the handler to the request, just poll it instead
704 var ival = setInterval(onreadystatechange, 13);
708 setTimeout(function(){
709 // Check to see if the request is still happening
711 // Cancel the request
715 onreadystatechange( "timeout" );
724 jQuery.handleError(s, xml, null, e);
727 // firefox 1.5 doesn't fire statechange for sync requests
729 onreadystatechange();
731 // return XMLHttpRequest to allow aborting the request etc.
735 handleError: function( s, xml, status, e ) {
736 // If a local callback was specified, fire it
737 if ( s.error ) s.error( xml, status, e );
739 // Fire the global callback
741 jQuery.event.trigger( "ajaxError", [xml, s, e] );
744 // Counter for holding the number of active queries
747 // Determines if an XMLHttpRequest was successful or not
748 httpSuccess: function( r ) {
750 return !r.status && location.protocol == "file:" ||
751 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
752 jQuery.browser.safari && r.status == undefined;
757 // Determines if an XMLHttpRequest returns NotModified
758 httpNotModified: function( xml, url ) {
760 var xmlRes = xml.getResponseHeader("Last-Modified");
762 // Firefox always returns 200. check Last-Modified date
763 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
764 jQuery.browser.safari && xml.status == undefined;
769 /* Get the data out of an XMLHttpRequest.
770 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
771 * otherwise return plain text.
772 * (String) data - The type of data that you're expecting back,
773 * (e.g. "xml", "html", "script")
775 httpData: function( r, type ) {
776 var ct = r.getResponseHeader("content-type");
777 var xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0;
778 data = xml ? r.responseXML : r.responseText;
780 if ( xml && data.documentElement.tagName == "parsererror" )
783 // If the type is "script", eval it in global context
784 if ( type == "script" )
785 jQuery.globalEval( data );
787 // Get the JavaScript object, if JSON is used.
788 if ( type == "json" )
789 data = eval("(" + data + ")");
794 // Serialize an array of form elements or a set of
795 // key/values into a query string
796 param: function( a ) {
799 // If an array was passed in, assume that it is an array
801 if ( a.constructor == Array || a.jquery )
802 // Serialize the form elements
803 jQuery.each( a, function(){
804 s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
807 // Otherwise, assume that it's an object of key/value pairs
809 // Serialize the key/values
811 // If the value is an array then the key names need to be repeated
812 if ( a[j] && a[j].constructor == Array )
813 jQuery.each( a[j], function(){
814 s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
817 s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j] ) );
819 // Return the resulting serialization