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 var off = url.indexOf(" ");
53 var selector = url.slice(off, url.length);
54 url = url.slice(0, off);
57 callback = callback || function(){};
59 // Default to a GET request
62 // If the second parameter was provided
65 if ( jQuery.isFunction( params ) ) {
66 // We assume that it's the callback
70 // Otherwise, build a param string
72 params = jQuery.param( params );
78 // Request the remote document
83 ifModified: ifModified,
84 complete: function(res, status){
85 // If successful, inject the HTML into all the matched elements
86 if ( status == "success" || !ifModified && status == "notmodified" )
87 // See if a selector was specified
89 // Create a dummy div to hold the results
91 // inject the contents of the document in, removing the scripts
92 // to avoid any 'Permission Denied' errors in IE
93 .append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
95 // Locate the specified elements
98 // If not, just inject the full result
101 // Add delay to account for Safari's delay in globalEval
102 setTimeout(function(){
103 self.each( callback, [res.responseText, status, res] );
111 * Serializes a set of input elements into a string of data.
112 * This will serialize all given elements.
114 * A serialization similar to the form submit of a browser is
115 * provided by the [http://www.malsup.com/jquery/form/ Form Plugin].
116 * It also takes multiple-selects
117 * into account, while this method recognizes only a single option.
119 * @example $("input[@type=text]").serialize();
120 * @before <input type='text' name='name' value='John'/>
121 * <input type='text' name='location' value='Boston'/>
122 * @after name=John&location=Boston
123 * @desc Serialize a selection of input elements to a string
129 serialize: function() {
130 return jQuery.param( this );
134 // This method no longer does anything - all script evaluation is
135 // taken care of within the HTML injection methods.
136 evalScripts: function(){}
140 // Attach a bunch of functions for handling common AJAX events
143 * Attach a function to be executed whenever an AJAX request begins
144 * and there is none already active.
146 * @example $("#loading").ajaxStart(function(){
149 * @desc Show a loading message whenever an AJAX request starts
150 * (and none is already active).
154 * @param Function callback The function to execute.
159 * Attach a function to be executed whenever all AJAX requests have ended.
161 * @example $("#loading").ajaxStop(function(){
164 * @desc Hide a loading message after all the AJAX requests have stopped.
168 * @param Function callback The function to execute.
173 * 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").ajaxComplete(function(request, settings){
179 * $(this).append("<li>Request Complete.</li>");
181 * @desc Show a message when an AJAX request completes.
185 * @param Function callback The function to execute.
190 * Attach a function to be executed whenever an AJAX request completes
193 * The XMLHttpRequest and settings used for that request are passed
194 * as arguments to the callback.
196 * @example $("#msg").ajaxSuccess(function(request, settings){
197 * $(this).append("<li>Successful Request!</li>");
199 * @desc Show a message when an AJAX request completes successfully.
203 * @param Function callback The function to execute.
208 * Attach a function to be executed whenever an AJAX request fails.
210 * The XMLHttpRequest and settings used for that request are passed
211 * as arguments to the callback. A third argument, an exception object,
212 * is passed if an exception occured while processing the request.
214 * @example $("#msg").ajaxError(function(request, settings){
215 * $(this).append("<li>Error requesting page " + settings.url + "</li>");
217 * @desc Show a message when an AJAX request fails.
221 * @param Function callback The function to execute.
226 * Attach a function to be executed before an AJAX request is sent.
228 * The XMLHttpRequest and settings used for that request are passed
229 * as arguments to the callback.
231 * @example $("#msg").ajaxSend(function(request, settings){
232 * $(this).append("<li>Starting request at " + settings.url + "</li>");
234 * @desc Show a message before an AJAX request is sent.
238 * @param Function callback The function to execute.
241 jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
242 jQuery.fn[o] = function(f){
243 return this.bind(o, f);
250 * Load a remote page using an HTTP GET request.
252 * This is an easy way to send a simple GET request to a server
253 * without having to use the more complex $.ajax function. It
254 * allows a single callback function to be specified that will
255 * be executed when the request is complete (and only if the response
256 * has a successful response code). If you need to have both error
257 * and success callbacks, you may want to use $.ajax.
259 * @example $.get("test.cgi");
261 * @example $.get("test.cgi", { name: "John", time: "2pm" } );
263 * @example $.get("test.cgi", function(data){
264 * alert("Data Loaded: " + data);
267 * @example $.get("test.cgi",
268 * { name: "John", time: "2pm" },
270 * alert("Data Loaded: " + data);
275 * @type XMLHttpRequest
276 * @param String url The URL of the page to load.
277 * @param Map params (optional) Key/value pairs that will be sent to the server.
278 * @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
281 get: function( url, data, callback, type, ifModified ) {
282 // shift arguments if data argument was ommited
283 if ( jQuery.isFunction( data ) ) {
294 ifModified: ifModified
299 * Load a remote page using an HTTP GET request, only if it hasn't
300 * been modified since it was last retrieved.
302 * @example $.getIfModified("test.html");
304 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } );
306 * @example $.getIfModified("test.cgi", function(data){
307 * alert("Data Loaded: " + data);
310 * @example $.getifModified("test.cgi",
311 * { name: "John", time: "2pm" },
313 * alert("Data Loaded: " + data);
317 * @name $.getIfModified
318 * @type XMLHttpRequest
319 * @param String url The URL of the page to load.
320 * @param Map params (optional) Key/value pairs that will be sent to the server.
321 * @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
325 getIfModified: function( url, data, callback, type ) {
326 return jQuery.get(url, data, callback, type, 1);
330 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
332 * Warning: Safari <= 2.0.x is unable to evaluate scripts in a global
333 * context synchronously. If you load functions via getScript, make sure
334 * to call them after a delay.
336 * @example $.getScript("test.js");
338 * @example $.getScript("test.js", function(){
339 * alert("Script loaded and executed.");
343 * @type XMLHttpRequest
344 * @param String url The URL of the page to load.
345 * @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
348 getScript: function( url, callback ) {
349 return jQuery.get(url, null, callback, "script");
353 * Load JSON data using an HTTP GET request.
355 * @example $.getJSON("test.js", function(json){
356 * alert("JSON Data: " + json.users[3].name);
359 * @example $.getJSON("test.js",
360 * { name: "John", time: "2pm" },
362 * alert("JSON Data: " + json.users[3].name);
367 * @type XMLHttpRequest
368 * @param String url The URL of the page to load.
369 * @param Map params (optional) Key/value pairs that will be sent to the server.
370 * @param Function callback A function to be executed whenever the data is loaded successfully.
373 getJSON: function( url, data, callback ) {
374 return jQuery.get(url, data, callback, "json");
378 * Load a remote page using an HTTP POST request.
380 * @example $.post("test.cgi");
382 * @example $.post("test.cgi", { name: "John", time: "2pm" } );
384 * @example $.post("test.cgi", function(data){
385 * alert("Data Loaded: " + data);
388 * @example $.post("test.cgi",
389 * { name: "John", time: "2pm" },
391 * alert("Data Loaded: " + data);
396 * @type XMLHttpRequest
397 * @param String url The URL of the page to load.
398 * @param Map params (optional) Key/value pairs that will be sent to the server.
399 * @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
402 post: function( url, data, callback, type ) {
403 if ( jQuery.isFunction( data ) ) {
418 * Set the timeout in milliseconds of all AJAX requests to a specific amount of time.
419 * This will make all future AJAX requests timeout after a specified amount
422 * Set to null or 0 to disable timeouts (default).
424 * You can manually abort requests with the XMLHttpRequest's (returned by
425 * all ajax functions) abort() method.
427 * Deprecated. Use $.ajaxSetup instead.
429 * @example $.ajaxTimeout( 5000 );
430 * @desc Make all AJAX requests timeout after 5 seconds.
432 * @name $.ajaxTimeout
434 * @param Number time How long before an AJAX request times out, in milliseconds.
438 ajaxTimeout: function( timeout ) {
439 jQuery.ajaxSettings.timeout = timeout;
443 * Setup global settings for AJAX requests.
445 * See $.ajax for a description of all available options.
447 * @example $.ajaxSetup( {
452 * $.ajax({ data: myData });
453 * @desc Sets the defaults for AJAX requests to the url "/xmlhttp/",
454 * disables global handlers and uses POST instead of GET. The following
455 * AJAX requests then sends some data without having to set anything else.
459 * @param Map settings Key/value pairs to use for all AJAX requests
462 ajaxSetup: function( settings ) {
463 jQuery.extend( jQuery.ajaxSettings, settings );
470 contentType: "application/x-www-form-urlencoded",
476 // Last-Modified header cache for next request
480 * Load a remote page using an HTTP request.
482 * This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for
483 * higher-level abstractions that are often easier to understand and use,
484 * but don't offer as much functionality (such as error callbacks).
486 * $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't
487 * need that object to manipulate directly, but it is available if you need to
488 * abort the request manually.
490 * '''Note:''' If you specify the dataType option described below, make sure
491 * the server sends the correct MIME type in the response (eg. xml as "text/xml").
492 * Sending the wrong MIME type can lead to unexpected problems in your script.
493 * See [[Specifying the Data Type for AJAX Requests]] for more information.
495 * Supported datatypes are (see dataType option):
497 * "xml": Returns a XML document that can be processed via jQuery.
499 * "html": Returns HTML as plain text, included script tags are evaluated.
501 * "script": Evaluates the response as Javascript and returns it as plain text.
503 * "json": Evaluates the response as JSON and returns a Javascript Object
505 * $.ajax() takes one argument, an object of key/value pairs, that are
506 * used to initalize and handle the request. These are all the key/values that can
509 * (String) url - The URL to request.
511 * (String) type - The type of request to make ("POST" or "GET"), default is "GET".
513 * (String) dataType - The type of data that you're expecting back from
514 * the server. No default: If the server sends xml, the responseXML, otherwise
515 * the responseText is passed to the success callback.
517 * (Boolean) ifModified - Allow the request to be successful only if the
518 * response has changed since the last request. This is done by checking the
519 * Last-Modified header. Default value is false, ignoring the header.
521 * (Number) timeout - Local timeout in milliseconds to override global timeout, eg. to give a
522 * single request a longer timeout while all others timeout after 1 second.
523 * See $.ajaxTimeout() for global timeouts.
525 * (Boolean) global - Whether to trigger global AJAX event handlers for
526 * this request, default is true. Set to false to prevent that global handlers
527 * like ajaxStart or ajaxStop are triggered.
529 * (Function) error - A function to be called if the request fails. The
530 * function gets passed tree arguments: The XMLHttpRequest object, a
531 * string describing the type of error that occurred and an optional
532 * exception object, if one occured.
534 * (Function) success - A function to be called if the request succeeds. The
535 * function gets passed one argument: The data returned from the server,
536 * formatted according to the 'dataType' parameter.
538 * (Function) complete - A function to be called when the request finishes. The
539 * function gets passed two arguments: The XMLHttpRequest object and a
540 * string describing the type of success of the request.
542 * (Object|String) data - Data to be sent to the server. Converted to a query
543 * string, if not already a string. Is appended to the url for GET-requests.
544 * See processData option to prevent this automatic processing.
546 * (String) contentType - When sending data to the server, use this content-type.
547 * Default is "application/x-www-form-urlencoded", which is fine for most cases.
549 * (Boolean) processData - By default, data passed in to the data option as an object
550 * other as string will be processed and transformed into a query string, fitting to
551 * the default content-type "application/x-www-form-urlencoded". If you want to send
552 * DOMDocuments, set this option to false.
554 * (Boolean) async - By default, all requests are sent asynchronous (set to true).
555 * If you need synchronous requests, set this option to false.
557 * (Function) beforeSend - A pre-callback to set custom headers etc., the
558 * XMLHttpRequest is passed as the only argument.
565 * @desc Load and execute a JavaScript file.
570 * data: "name=John&location=Boston",
571 * success: function(msg){
572 * alert( "Data Saved: " + msg );
575 * @desc Save some data to the server and notify the user once its complete.
577 * @example var html = $.ajax({
581 * @desc Loads data synchronously. Blocks the browser while the requests is active.
582 * It is better to block user interaction by other means when synchronization is
585 * @example var xmlDocument = [create xml document];
588 * processData: false,
590 * success: handleResponse
592 * @desc Sends an xml document as data to the server. By setting the processData
593 * option to false, the automatic conversion of data to strings is prevented.
596 * @type XMLHttpRequest
597 * @param Map properties Key/value pairs to initialize the request with.
599 * @see ajaxSetup(Map)
601 ajax: function( s ) {
602 // Extend the settings, but re-extend 's' so that it can be
603 // checked again later (in the test suite, specifically)
604 s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
608 // convert data if not already a string
609 if ( s.processData && typeof s.data != "string" )
610 s.data = jQuery.param(s.data);
612 // append data to url for get requests
613 if ( s.type.toLowerCase() == "get" ) {
614 // "?" + data or "&" + data (in case there are already params)
615 s.url += (s.url.indexOf("?") > -1 ? "&" : "?") + s.data;
617 // IE likes to send both get and post data, prevent this
622 // Watch for a new set of requests
623 if ( s.global && ! jQuery.active++ )
624 jQuery.event.trigger( "ajaxStart" );
626 var requestDone = false;
628 // Create the request object; Microsoft failed to properly
629 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
630 var xml = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
633 xml.open(s.type, s.url, s.async);
635 // Set the correct header, if data is being sent
637 xml.setRequestHeader("Content-Type", s.contentType);
639 // Set the If-Modified-Since header, if ifModified mode.
641 xml.setRequestHeader("If-Modified-Since",
642 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
644 // Set header so the called script knows that it's an XMLHttpRequest
645 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
647 // Allow custom headers/mimetypes
652 jQuery.event.trigger("ajaxSend", [xml, s]);
654 // Wait for a response to come back
655 var onreadystatechange = function(isTimeout){
656 // The transfer is complete and the data is available, or the request timed out
657 if ( !requestDone && xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
660 // clear poll interval
666 var status = isTimeout == "timeout" && "timeout" ||
667 !jQuery.httpSuccess( xml ) && "error" ||
668 s.ifModified && jQuery.httpNotModified( xml, s.url ) && "notmodified" ||
671 if ( status == "success" ) {
672 // Watch for, and catch, XML document parse errors
674 // process the data (runs the xml through httpData regardless of callback)
675 var data = jQuery.httpData( xml, s.dataType );
677 status = "parsererror";
681 // Make sure that the request was successful or notmodified
682 if ( status == "success" ) {
683 // Cache Last-Modified header, if ifModified mode.
686 modRes = xml.getResponseHeader("Last-Modified");
687 } catch(e) {} // swallow exception thrown by FF if header is not available
689 if ( s.ifModified && modRes )
690 jQuery.lastModified[s.url] = modRes;
692 // If a local callback was specified, fire it and pass it the data
694 s.success( data, status );
696 // Fire the global callback
698 jQuery.event.trigger( "ajaxSuccess", [xml, s] );
700 jQuery.handleError(s, xml, status);
702 // The request was completed
704 jQuery.event.trigger( "ajaxComplete", [xml, s] );
706 // Handle the global AJAX counter
707 if ( s.global && ! --jQuery.active )
708 jQuery.event.trigger( "ajaxStop" );
712 s.complete(xml, status);
721 // don't attach the handler to the request, just poll it instead
722 var ival = setInterval(onreadystatechange, 13);
726 setTimeout(function(){
727 // Check to see if the request is still happening
729 // Cancel the request
733 onreadystatechange( "timeout" );
742 jQuery.handleError(s, xml, null, e);
745 // firefox 1.5 doesn't fire statechange for sync requests
747 onreadystatechange();
749 // return XMLHttpRequest to allow aborting the request etc.
753 handleError: function( s, xml, status, e ) {
754 // If a local callback was specified, fire it
755 if ( s.error ) s.error( xml, status, e );
757 // Fire the global callback
759 jQuery.event.trigger( "ajaxError", [xml, s, e] );
762 // Counter for holding the number of active queries
765 // Determines if an XMLHttpRequest was successful or not
766 httpSuccess: function( r ) {
768 return !r.status && location.protocol == "file:" ||
769 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
770 jQuery.browser.safari && r.status == undefined;
775 // Determines if an XMLHttpRequest returns NotModified
776 httpNotModified: function( xml, url ) {
778 var xmlRes = xml.getResponseHeader("Last-Modified");
780 // Firefox always returns 200. check Last-Modified date
781 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
782 jQuery.browser.safari && xml.status == undefined;
787 /* Get the data out of an XMLHttpRequest.
788 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
789 * otherwise return plain text.
790 * (String) data - The type of data that you're expecting back,
791 * (e.g. "xml", "html", "script")
793 httpData: function( r, type ) {
794 var ct = r.getResponseHeader("content-type");
795 var xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0;
796 data = xml ? r.responseXML : r.responseText;
798 if ( xml && data.documentElement.tagName == "parsererror" )
801 // If the type is "script", eval it in global context
802 if ( type == "script" )
803 jQuery.globalEval( data );
805 // Get the JavaScript object, if JSON is used.
806 if ( type == "json" )
807 data = eval("(" + data + ")");
812 // Serialize an array of form elements or a set of
813 // key/values into a query string
814 param: function( a ) {
817 // If an array was passed in, assume that it is an array
819 if ( a.constructor == Array || a.jquery )
820 // Serialize the form elements
821 jQuery.each( a, function(){
822 s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
825 // Otherwise, assume that it's an object of key/value pairs
827 // Serialize the key/values
829 // If the value is an array then the key names need to be repeated
830 if ( a[j] && a[j].constructor == Array )
831 jQuery.each( a[j], function(){
832 s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
835 s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j] ) );
837 // Return the resulting serialization