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 ( url.constructor == Function )
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 ( params.constructor == Function ) {
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 form plugin. It also takes multiple-selects
98 * into account, while this method recognizes only a single option.
100 * @example $("input[@type=text]").serialize();
101 * @before <input type='text' name='name' value='John'/>
102 * <input type='text' name='location' value='Boston'/>
103 * @after name=John&location=Boston
104 * @desc Serialize a selection of input elements to a string
110 serialize: function() {
111 return jQuery.param( this );
115 * Evaluate all script tags inside this jQuery. If they have a src attribute,
116 * the script is loaded, otherwise it's content is evaluated.
123 evalScripts: function() {
124 return this.find('script').each(function(){
126 jQuery.getScript( this.src );
128 jQuery.globalEval( this.text || this.textContent || this.innerHTML || "" );
134 // If IE is used, create a wrapper for the XMLHttpRequest object
135 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
136 XMLHttpRequest = function(){
137 return new ActiveXObject("Microsoft.XMLHTTP");
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 send.
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 send.
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 * @example $.get("test.cgi");
254 * @example $.get("test.cgi", { name: "John", time: "2pm" } );
256 * @example $.get("test.cgi", function(data){
257 * alert("Data Loaded: " + data);
260 * @example $.get("test.cgi",
261 * { name: "John", time: "2pm" },
263 * alert("Data Loaded: " + data);
268 * @type XMLHttpRequest
269 * @param String url The URL of the page to load.
270 * @param Map params (optional) Key/value pairs that will be sent to the server.
271 * @param Function callback (optional) A function to be executed whenever the data is loaded.
274 get: function( url, data, callback, type, ifModified ) {
275 // shift arguments if data argument was ommited
276 if ( data && data.constructor == Function ) {
286 ifModified: ifModified
291 * Load a remote page using an HTTP GET request, only if it hasn't
292 * been modified since it was last retrieved.
294 * @example $.getIfModified("test.html");
296 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } );
298 * @example $.getIfModified("test.cgi", function(data){
299 * alert("Data Loaded: " + data);
302 * @example $.getifModified("test.cgi",
303 * { name: "John", time: "2pm" },
305 * alert("Data Loaded: " + data);
309 * @name $.getIfModified
310 * @type XMLHttpRequest
311 * @param String url The URL of the page to load.
312 * @param Map params (optional) Key/value pairs that will be sent to the server.
313 * @param Function callback (optional) A function to be executed whenever the data is loaded.
316 getIfModified: function( url, data, callback, type ) {
317 return jQuery.get(url, data, callback, type, 1);
321 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
323 * Warning: Safari <= 2.0.x is unable to evalulate scripts in a global
324 * context synchronously. If you load functions via getScript, make sure
325 * to call them after a delay.
327 * @example $.getScript("test.js");
329 * @example $.getScript("test.js", function(){
330 * alert("Script loaded and executed.");
334 * @type XMLHttpRequest
335 * @param String url The URL of the page to load.
336 * @param Function callback (optional) A function to be executed whenever the data is loaded.
339 getScript: function( url, callback ) {
340 return jQuery.get(url, null, callback, "script");
344 * Load JSON data using an HTTP GET request.
346 * @example $.getJSON("test.js", function(json){
347 * alert("JSON Data: " + json.users[3].name);
350 * @example $.getJSON("test.js",
351 * { name: "John", time: "2pm" },
353 * alert("JSON Data: " + json.users[3].name);
358 * @type XMLHttpRequest
359 * @param String url The URL of the page to load.
360 * @param Map params (optional) Key/value pairs that will be sent to the server.
361 * @param Function callback A function to be executed whenever the data is loaded.
364 getJSON: function( url, data, callback ) {
365 return jQuery.get(url, data, callback, "json");
369 * Load a remote page using an HTTP POST request.
371 * @example $.post("test.cgi");
373 * @example $.post("test.cgi", { name: "John", time: "2pm" } );
375 * @example $.post("test.cgi", function(data){
376 * alert("Data Loaded: " + data);
379 * @example $.post("test.cgi",
380 * { name: "John", time: "2pm" },
382 * alert("Data Loaded: " + data);
387 * @type XMLHttpRequest
388 * @param String url The URL of the page to load.
389 * @param Map params (optional) Key/value pairs that will be sent to the server.
390 * @param Function callback (optional) A function to be executed whenever the data is loaded.
393 post: function( url, data, callback, type ) {
407 * Set the timeout of all AJAX requests to a specific amount of time.
408 * This will make all future AJAX requests timeout after a specified amount
411 * Set to null or 0 to disable timeouts (default).
413 * You can manually abort requests with the XMLHttpRequest's (returned by
414 * all ajax functions) abort() method.
416 * Deprecated. Use $.ajaxSetup instead.
418 * @example $.ajaxTimeout( 5000 );
419 * @desc Make all AJAX requests timeout after 5 seconds.
421 * @name $.ajaxTimeout
423 * @param Number time How long before an AJAX request times out.
426 ajaxTimeout: function( timeout ) {
427 jQuery.ajaxSettings.timeout = timeout;
431 * Setup global settings for AJAX requests.
433 * See $.ajax for a description of all available options.
435 * @example $.ajaxSetup( {
440 * $.ajax({ data: myData });
441 * @desc Sets the defaults for AJAX requests to the url "/xmlhttp/",
442 * disables global handlers and uses POST instead of GET. The following
443 * AJAX requests then sends some data without having to set anything else.
447 * @param Map settings Key/value pairs to use for all AJAX requests
450 ajaxSetup: function( settings ) {
451 jQuery.extend( jQuery.ajaxSettings, settings );
458 contentType: "application/x-www-form-urlencoded",
463 // Last-Modified header cache for next request
467 * Load a remote page using an HTTP request.
469 * This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for
470 * higher-level abstractions.
472 * $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't
473 * need that object to manipulate directly, but it is available if you need to
474 * abort the request manually.
476 * Note: Make sure the server sends the right mimetype (eg. xml as
477 * "text/xml"). Sending the wrong mimetype will get you into serious
478 * trouble that jQuery can't solve.
480 * Supported datatypes are (see dataType option):
482 * "xml": Returns a XML document that can be processed via jQuery.
484 * "html": Returns HTML as plain text, included script tags are evaluated.
486 * "script": Evaluates the response as Javascript and returns it as plain text.
488 * "json": Evaluates the response as JSON and returns a Javascript Object
490 * $.ajax() takes one argument, an object of key/value pairs, that are
491 * used to initalize and handle the request. These are all the key/values that can
494 * (String) url - The URL to request.
496 * (String) type - The type of request to make ("POST" or "GET"), default is "GET".
498 * (String) dataType - The type of data that you're expecting back from
499 * the server. No default: If the server sends xml, the responseXML, otherwise
500 * the responseText is passed to the success callback.
502 * (Boolean) ifModified - Allow the request to be successful only if the
503 * response has changed since the last request. This is done by checking the
504 * Last-Modified header. Default value is false, ignoring the header.
506 * (Number) timeout - Local timeout to override global timeout, eg. to give a
507 * single request a longer timeout while all others timeout after 1 second.
508 * See $.ajaxTimeout() for global timeouts.
510 * (Boolean) global - Whether to trigger global AJAX event handlers for
511 * this request, default is true. Set to false to prevent that global handlers
512 * like ajaxStart or ajaxStop are triggered.
514 * (Function) error - A function to be called if the request fails. The
515 * function gets passed tree arguments: The XMLHttpRequest object, a
516 * string describing the type of error that occurred and an optional
517 * exception object, if one occured.
519 * (Function) success - A function to be called if the request succeeds. The
520 * function gets passed one argument: The data returned from the server,
521 * formatted according to the 'dataType' parameter.
523 * (Function) complete - A function to be called when the request finishes. The
524 * function gets passed two arguments: The XMLHttpRequest object and a
525 * string describing the type of success of the request.
527 * (Object|String) data - Data to be sent to the server. Converted to a query
528 * string, if not already a string. Is appended to the url for GET-requests.
529 * See processData option to prevent this automatic processing.
531 * (String) contentType - When sending data to the server, use this content-type.
532 * Default is "application/x-www-form-urlencoded", which is fine for most cases.
534 * (Boolean) processData - By default, data passed in to the data option as an object
535 * other as string will be processed and transformed into a query string, fitting to
536 * the default content-type "application/x-www-form-urlencoded". If you want to send
537 * DOMDocuments, set this option to false.
539 * (Boolean) async - By default, all requests are send asynchronous (set to true).
540 * If you need synchronous requests, set this option to false.
542 * (Function) beforeSend - A pre-callback to set custom headers etc., the
543 * XMLHttpRequest is passed as the only argument.
550 * @desc Load and execute a JavaScript file.
555 * data: "name=John&location=Boston",
556 * success: function(msg){
557 * alert( "Data Saved: " + msg );
560 * @desc Save some data to the server and notify the user once its complete.
562 * @example var html = $.ajax({
566 * @desc Loads data synchronously. Blocks the browser while the requests is active.
567 * It is better to block user interaction with others means when synchronization is
568 * necessary, instead to block the complete browser.
570 * @example var xmlDocument = [create xml document];
573 * processData: false,
575 * success: handleResponse
577 * @desc Sends an xml document as data to the server. By setting the processData
578 * option to false, the automatic conversion of data to strings is prevented.
581 * @type XMLHttpRequest
582 * @param Map properties Key/value pairs to initialize the request with.
584 * @see ajaxSetup(Map)
586 ajax: function( s ) {
587 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
588 s = jQuery.extend({}, jQuery.ajaxSettings, s);
592 // convert data if not already a string
593 if (s.processData && typeof s.data != 'string')
594 s.data = jQuery.param(s.data);
595 // append data to url for get requests
596 if( s.type.toLowerCase() == "get" )
597 // "?" + data or "&" + data (in case there are already params)
598 s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data;
601 // Watch for a new set of requests
602 if ( s.global && ! jQuery.active++ )
603 jQuery.event.trigger( "ajaxStart" );
605 var requestDone = false;
607 // Create the request object
608 var xml = new XMLHttpRequest();
611 xml.open(s.type, s.url, s.async);
613 // Set the correct header, if data is being sent
615 xml.setRequestHeader("Content-Type", s.contentType);
617 // Set the If-Modified-Since header, if ifModified mode.
619 xml.setRequestHeader("If-Modified-Since",
620 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
622 // Set header so the called script knows that it's an XMLHttpRequest
623 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
625 // Make sure the browser sends the right content length
626 if ( xml.overrideMimeType )
627 xml.setRequestHeader("Connection", "close");
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 ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
643 status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
644 s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
645 // Make sure that the request was successful or notmodified
646 if ( status != "error" ) {
647 // Cache Last-Modified header, if ifModified mode.
650 modRes = xml.getResponseHeader("Last-Modified");
651 } catch(e) {} // swallow exception thrown by FF if header is not available
653 if ( s.ifModified && modRes )
654 jQuery.lastModified[s.url] = modRes;
656 // process the data (runs the xml through httpData regardless of callback)
657 var data = jQuery.httpData( xml, s.dataType );
659 // If a local callback was specified, fire it and pass it the data
661 s.success( data, status );
663 // Fire the global callback
665 jQuery.event.trigger( "ajaxSuccess", [xml, s] );
667 jQuery.handleError(s, xml, status);
670 jQuery.handleError(s, xml, status, e);
673 // The request was completed
675 jQuery.event.trigger( "ajaxComplete", [xml, s] );
677 // Handle the global AJAX counter
678 if ( s.global && ! --jQuery.active )
679 jQuery.event.trigger( "ajaxStop" );
683 s.complete(xml, status);
686 xml.onreadystatechange = function(){};
690 xml.onreadystatechange = onreadystatechange;
694 setTimeout(function(){
695 // Check to see if the request is still happening
697 // Cancel the request
701 onreadystatechange( "timeout" );
705 // save non-leaking reference
712 jQuery.handleError(s, xml, null, e);
715 // firefox 1.5 doesn't fire statechange for sync requests
717 onreadystatechange();
719 // return XMLHttpRequest to allow aborting the request etc.
723 handleError: function( s, xml, status, e ) {
724 // If a local callback was specified, fire it
725 if ( s.error ) s.error( xml, status, e );
727 // Fire the global callback
729 jQuery.event.trigger( "ajaxError", [xml, s, e] );
732 // Counter for holding the number of active queries
735 // Determines if an XMLHttpRequest was successful or not
736 httpSuccess: function( r ) {
738 return !r.status && location.protocol == "file:" ||
739 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
740 jQuery.browser.safari && r.status == undefined;
745 // Determines if an XMLHttpRequest returns NotModified
746 httpNotModified: function( xml, url ) {
748 var xmlRes = xml.getResponseHeader("Last-Modified");
750 // Firefox always returns 200. check Last-Modified date
751 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
752 jQuery.browser.safari && xml.status == undefined;
757 /* Get the data out of an XMLHttpRequest.
758 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
759 * otherwise return plain text.
760 * (String) data - The type of data that you're expecting back,
761 * (e.g. "xml", "html", "script")
763 httpData: function( r, type ) {
764 var ct = r.getResponseHeader("content-type");
765 var data = !type && ct && ct.indexOf("xml") >= 0;
766 data = type == "xml" || data ? r.responseXML : r.responseText;
768 // If the type is "script", eval it in global context
769 if ( type == "script" )
770 jQuery.globalEval( data );
772 // Get the JavaScript object, if JSON is used.
773 if ( type == "json" )
774 eval( "data = " + data );
776 // evaluate scripts within html
777 if ( type == "html" )
778 jQuery("<div>").html(data).evalScripts();
783 // Serialize an array of form elements or a set of
784 // key/values into a query string
785 param: function( a ) {
788 // If an array was passed in, assume that it is an array
790 if ( a.constructor == Array || a.jquery )
791 // Serialize the form elements
792 for ( var i = 0; i < a.length; i++ )
793 s.push( encodeURIComponent(a[i].name) + "=" + encodeURIComponent( a[i].value ) );
795 // Otherwise, assume that it's an object of key/value pairs
797 // Serialize the key/values
799 // If the value is an array then the key names need to be repeated
800 if ( a[j].constructor == Array )
801 for ( var k = 0; k < a[j].length; k++ )
802 s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j][k] ) );
804 s.push( encodeURIComponent(j) + "=" + encodeURIComponent( a[j] ) );
806 // Return the resulting serialization
810 // evalulates a script in global context
811 // not reliable for safari
812 globalEval: function( data ) {
813 if ( window.execScript )
814 window.execScript( data );
815 else if ( jQuery.browser.safari )
816 // safari doesn't provide a synchronous global eval
817 window.setTimeout( data, 0 );
819 eval.call( window, data );