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).
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 * Note: Avoid to use this to load scripts, instead use $.getScript.
26 * IE strips script tags when there aren't any other characters in front of it.
28 * @example $("#feeds").load("feeds.html");
29 * @before <div id="feeds"></div>
30 * @result <div id="feeds"><b>45</b> feeds found.</div>
32 * @example $("#feeds").load("feeds.html",
34 * function() { alert("The last 25 entries in the feed have been loaded"); }
36 * @desc Same as above, but with an additional parameter
37 * and a callback that is executed when the data was loaded.
41 * @param String url The URL of the HTML file to load.
42 * @param Object params (optional) A set of key/value pairs that will be sent as data to the server.
43 * @param Function callback (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).
46 load: function( url, params, callback, ifModified ) {
47 if ( jQuery.isFunction( url ) )
48 return this.bind("load", url);
50 callback = callback || function(){};
52 // Default to a GET request
55 // If the second parameter was provided
58 if ( jQuery.isFunction( params ) ) {
59 // We assume that it's the callback
63 // Otherwise, build a param string
65 params = jQuery.param( params );
71 // Request the remote document
76 ifModified: ifModified,
77 complete: function(res, status){
78 if ( status == "success" || !ifModified && status == "notmodified" )
79 // Inject the HTML into all the matched elements
80 self.attr("innerHTML", res.responseText)
81 // Execute all the scripts inside of the newly-injected HTML
84 .each( callback, [res.responseText, status, res] );
86 callback.apply( self, [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 * Evaluate all script tags inside this jQuery. If they have a src attribute,
117 * the script is loaded, otherwise it's content is evaluated.
124 evalScripts: function() {
125 return this.find("script").each(function(){
127 jQuery.getScript( this.src );
129 jQuery.globalEval( this.text || this.textContent || this.innerHTML || "" );
135 // Attach a bunch of functions for handling common AJAX events
138 * Attach a function to be executed whenever an AJAX request begins
139 * and there is none already active.
141 * @example $("#loading").ajaxStart(function(){
144 * @desc Show a loading message whenever an AJAX request starts
145 * (and none is already active).
149 * @param Function callback The function to execute.
154 * Attach a function to be executed whenever all AJAX requests have ended.
156 * @example $("#loading").ajaxStop(function(){
159 * @desc Hide a loading message after all the AJAX requests have stopped.
163 * @param Function callback The function to execute.
168 * Attach a function to be executed whenever an AJAX request completes.
170 * The XMLHttpRequest and settings used for that request are passed
171 * as arguments to the callback.
173 * @example $("#msg").ajaxComplete(function(request, settings){
174 * $(this).append("<li>Request Complete.</li>");
176 * @desc Show a message when an AJAX request completes.
180 * @param Function callback The function to execute.
185 * Attach a function to be executed whenever an AJAX request completes
188 * The XMLHttpRequest and settings used for that request are passed
189 * as arguments to the callback.
191 * @example $("#msg").ajaxSuccess(function(request, settings){
192 * $(this).append("<li>Successful Request!</li>");
194 * @desc Show a message when an AJAX request completes successfully.
198 * @param Function callback The function to execute.
203 * Attach a function to be executed whenever an AJAX request fails.
205 * The XMLHttpRequest and settings used for that request are passed
206 * as arguments to the callback. A third argument, an exception object,
207 * is passed if an exception occured while processing the request.
209 * @example $("#msg").ajaxError(function(request, settings){
210 * $(this).append("<li>Error requesting page " + settings.url + "</li>");
212 * @desc Show a message when an AJAX request fails.
216 * @param Function callback The function to execute.
221 * Attach a function to be executed before an AJAX request is sent.
223 * The XMLHttpRequest and settings used for that request are passed
224 * as arguments to the callback.
226 * @example $("#msg").ajaxSend(function(request, settings){
227 * $(this).append("<li>Starting request at " + settings.url + "</li>");
229 * @desc Show a message before an AJAX request is sent.
233 * @param Function callback The function to execute.
236 jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
237 jQuery.fn[o] = function(f){
238 return this.bind(o, f);
245 * Load a remote page using an HTTP GET request.
247 * This is an easy way to send a simple GET request to a server
248 * without having to use the more complex $.ajax function. It
249 * allows a single callback function to be specified that will
250 * be executed when the request is complete (and only if the response
251 * has a successful response code). If you need to have both error
252 * and success callbacks, you may want to use $.ajax.
254 * @example $.get("test.cgi");
256 * @example $.get("test.cgi", { name: "John", time: "2pm" } );
258 * @example $.get("test.cgi", function(data){
259 * alert("Data Loaded: " + data);
262 * @example $.get("test.cgi",
263 * { name: "John", time: "2pm" },
265 * alert("Data Loaded: " + data);
270 * @type XMLHttpRequest
271 * @param String url The URL of the page to load.
272 * @param Map params (optional) Key/value pairs that will be sent to the server.
273 * @param Function callback (optional) A function to be executed whenever the data is loaded successfully.
276 get: function( url, data, callback, type, ifModified ) {
277 // shift arguments if data argument was ommited
278 if ( jQuery.isFunction( data ) ) {
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 Map params (optional) 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 successfully.
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 evaluate 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 successfully.
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 Map params (optional) Key/value pairs that will be sent to the server.
364 * @param Function callback A function to be executed whenever the data is loaded successfully.
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 Map params (optional) 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 successfully.
396 post: function( url, data, callback, type ) {
397 if ( jQuery.isFunction( data ) ) {
415 * Set the timeout in milliseconds of all AJAX requests to a specific amount of time.
416 * This will make all future AJAX requests timeout after a specified amount
419 * Set to null or 0 to disable timeouts (default).
421 * You can manually abort requests with the XMLHttpRequest's (returned by
422 * all ajax functions) abort() method.
424 * Deprecated. Use $.ajaxSetup instead.
426 * @example $.ajaxTimeout( 5000 );
427 * @desc Make all AJAX requests timeout after 5 seconds.
429 * @name $.ajaxTimeout
431 * @param Number time How long before an AJAX request times out, in milliseconds.
434 ajaxTimeout: function( timeout ) {
435 jQuery.ajaxSettings.timeout = timeout;
439 * Setup global settings for AJAX requests.
441 * See $.ajax for a description of all available options.
443 * @example $.ajaxSetup( {
448 * $.ajax({ data: myData });
449 * @desc Sets the defaults for AJAX requests to the url "/xmlhttp/",
450 * disables global handlers and uses POST instead of GET. The following
451 * AJAX requests then sends some data without having to set anything else.
455 * @param Map settings Key/value pairs to use for all AJAX requests
458 ajaxSetup: function( settings ) {
459 jQuery.extend( jQuery.ajaxSettings, settings );
466 contentType: "application/x-www-form-urlencoded",
472 // Last-Modified header cache for next request
476 * Load a remote page using an HTTP request.
478 * This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for
479 * higher-level abstractions that are often easier to understand and use,
480 * but don't offer as much functionality (such as error callbacks).
482 * $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't
483 * need that object to manipulate directly, but it is available if you need to
484 * abort the request manually.
486 * '''Note:''' If you specify the dataType option described below, make sure
487 * the server sends the correct MIME type in the response (eg. xml as "text/xml").
488 * Sending the wrong MIME type can lead to unexpected problems in your script.
489 * See [[Specifying the Data Type for AJAX Requests]] for more information.
491 * Supported datatypes are (see dataType option):
493 * "xml": Returns a XML document that can be processed via jQuery.
495 * "html": Returns HTML as plain text, included script tags are evaluated.
497 * "script": Evaluates the response as Javascript and returns it as plain text.
499 * "json": Evaluates the response as JSON and returns a Javascript Object
501 * $.ajax() takes one argument, an object of key/value pairs, that are
502 * used to initalize and handle the request. These are all the key/values that can
505 * (String) url - The URL to request.
507 * (String) type - The type of request to make ("POST" or "GET"), default is "GET".
509 * (String) dataType - The type of data that you're expecting back from
510 * the server. No default: If the server sends xml, the responseXML, otherwise
511 * the responseText is passed to the success callback.
513 * (Boolean) ifModified - Allow the request to be successful only if the
514 * response has changed since the last request. This is done by checking the
515 * Last-Modified header. Default value is false, ignoring the header.
517 * (Number) timeout - Local timeout in milliseconds to override global timeout, eg. to give a
518 * single request a longer timeout while all others timeout after 1 second.
519 * See $.ajaxTimeout() for global timeouts.
521 * (Boolean) global - Whether to trigger global AJAX event handlers for
522 * this request, default is true. Set to false to prevent that global handlers
523 * like ajaxStart or ajaxStop are triggered.
525 * (Function) error - A function to be called if the request fails. The
526 * function gets passed tree arguments: The XMLHttpRequest object, a
527 * string describing the type of error that occurred and an optional
528 * exception object, if one occured.
530 * (Function) success - A function to be called if the request succeeds. The
531 * function gets passed one argument: The data returned from the server,
532 * formatted according to the 'dataType' parameter.
534 * (Function) complete - A function to be called when the request finishes. The
535 * function gets passed two arguments: The XMLHttpRequest object and a
536 * string describing the type of success of the request.
538 * (Object|String) data - Data to be sent to the server. Converted to a query
539 * string, if not already a string. Is appended to the url for GET-requests.
540 * See processData option to prevent this automatic processing.
542 * (String) contentType - When sending data to the server, use this content-type.
543 * Default is "application/x-www-form-urlencoded", which is fine for most cases.
545 * (Boolean) processData - By default, data passed in to the data option as an object
546 * other as string will be processed and transformed into a query string, fitting to
547 * the default content-type "application/x-www-form-urlencoded". If you want to send
548 * DOMDocuments, set this option to false.
550 * (Boolean) async - By default, all requests are sent asynchronous (set to true).
551 * If you need synchronous requests, set this option to false.
553 * (Function) beforeSend - A pre-callback to set custom headers etc., the
554 * XMLHttpRequest is passed as the only argument.
561 * @desc Load and execute a JavaScript file.
566 * data: "name=John&location=Boston",
567 * success: function(msg){
568 * alert( "Data Saved: " + msg );
571 * @desc Save some data to the server and notify the user once its complete.
573 * @example var html = $.ajax({
577 * @desc Loads data synchronously. Blocks the browser while the requests is active.
578 * It is better to block user interaction by other means when synchronization is
581 * @example var xmlDocument = [create xml document];
584 * processData: false,
586 * success: handleResponse
588 * @desc Sends an xml document as data to the server. By setting the processData
589 * option to false, the automatic conversion of data to strings is prevented.
592 * @type XMLHttpRequest
593 * @param Map properties Key/value pairs to initialize the request with.
595 * @see ajaxSetup(Map)
597 ajax: function( s ) {
598 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
599 s = jQuery.extend({}, jQuery.ajaxSettings, s);
603 // convert data if not already a string
604 if (s.processData && typeof s.data != "string")
605 s.data = jQuery.param(s.data);
606 // append data to url for get requests
607 if( s.type.toLowerCase() == "get" ) {
608 // "?" + data or "&" + data (in case there are already params)
609 s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data;
610 // IE likes to send both get and post data, prevent this
615 // Watch for a new set of requests
616 if ( s.global && ! jQuery.active++ )
617 jQuery.event.trigger( "ajaxStart" );
619 var requestDone = false;
621 // Create the request object; Microsoft failed to properly
622 // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
623 var xml = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
626 xml.open(s.type, s.url, s.async);
628 // Set the correct header, if data is being sent
630 xml.setRequestHeader("Content-Type", s.contentType);
632 // Set the If-Modified-Since header, if ifModified mode.
634 xml.setRequestHeader("If-Modified-Since",
635 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
637 // Set header so the called script knows that it's an XMLHttpRequest
638 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
640 // Allow custom headers/mimetypes
645 jQuery.event.trigger("ajaxSend", [xml, s]);
647 // Wait for a response to come back
648 var onreadystatechange = function(isTimeout){
649 // The transfer is complete and the data is available, or the request timed out
650 if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
653 // clear poll interval
661 status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
662 s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
663 // Make sure that the request was successful or notmodified
664 if ( status != "error" ) {
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 // process the data (runs the xml through httpData regardless of callback)
675 var data = jQuery.httpData( xml, s.dataType );
677 // If a local callback was specified, fire it and pass it the data
679 s.success( data, status );
681 // Fire the global callback
683 jQuery.event.trigger( "ajaxSuccess", [xml, s] );
685 jQuery.handleError(s, xml, status);
688 jQuery.handleError(s, xml, status, e);
691 // The request was completed
693 jQuery.event.trigger( "ajaxComplete", [xml, s] );
695 // Handle the global AJAX counter
696 if ( s.global && ! --jQuery.active )
697 jQuery.event.trigger( "ajaxStop" );
701 s.complete(xml, status);
709 // don't attach the handler to the request, just poll it instead
710 var ival = setInterval(onreadystatechange, 13);
714 setTimeout(function(){
715 // Check to see if the request is still happening
717 // Cancel the request
721 onreadystatechange( "timeout" );
729 jQuery.handleError(s, xml, null, e);
732 // firefox 1.5 doesn't fire statechange for sync requests
734 onreadystatechange();
736 // return XMLHttpRequest to allow aborting the request etc.
740 handleError: function( s, xml, status, e ) {
741 // If a local callback was specified, fire it
742 if ( s.error ) s.error( xml, status, e );
744 // Fire the global callback
746 jQuery.event.trigger( "ajaxError", [xml, s, e] );
749 // Counter for holding the number of active queries
752 // Determines if an XMLHttpRequest was successful or not
753 httpSuccess: function( r ) {
755 return !r.status && location.protocol == "file:" ||
756 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
757 jQuery.browser.safari && r.status == undefined;
762 // Determines if an XMLHttpRequest returns NotModified
763 httpNotModified: function( xml, url ) {
765 var xmlRes = xml.getResponseHeader("Last-Modified");
767 // Firefox always returns 200. check Last-Modified date
768 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
769 jQuery.browser.safari && xml.status == undefined;
774 /* Get the data out of an XMLHttpRequest.
775 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
776 * otherwise return plain text.
777 * (String) data - The type of data that you're expecting back,
778 * (e.g. "xml", "html", "script")
780 httpData: function( r, type ) {
781 var ct = r.getResponseHeader("content-type");
782 var data = !type && ct && ct.indexOf("xml") >= 0;
783 data = type == "xml" || data ? r.responseXML : r.responseText;
785 // If the type is "script", eval it in global context
786 if ( type == "script" )
787 jQuery.globalEval( data );
789 // Get the JavaScript object, if JSON is used.
790 if ( type == "json" )
791 eval( "data = " + data );
793 // evaluate scripts within html
794 if ( type == "html" )
795 jQuery("<div>").html(data).evalScripts();
800 // Serialize an array of form elements or a set of
801 // key/values into a query string
802 param: function( a ) {
805 // If an array was passed in, assume that it is an array
807 if ( a.constructor == Array || a.jquery )
808 // Serialize the form elements
809 jQuery.each( a, function(){
810 s.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( this.value ) );
813 // Otherwise, assume that it's an object of key/value pairs
815 // Serialize the key/values
817 // If the value is an array then the key names need to be repeated
818 if ( a[j] && a[j].constructor == Array )
819 jQuery.each( a[j], function(){
820 s.push( encodeURIComponent(j) + "=" + encodeURIComponent( this ) );
823 s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j] ) );
825 // Return the resulting serialization
829 // evalulates a script in global context
830 // not reliable for safari
831 globalEval: function( data ) {
832 if ( window.execScript )
833 window.execScript( data );
834 else if ( jQuery.browser.safari )
835 // safari doesn't provide a synchronous global eval
836 window.setTimeout( data, 0 );
838 eval.call( window, data );