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. A third argument, an exception object,
211 * is passed if an exception occured while processing the request.
213 * @example $("#msg").ajaxError(function(request, settings){
214 * $(this).append("<li>Error requesting page " + settings.url + "</li>");
216 * @desc Show a message when an AJAX request fails.
220 * @param Function callback The function to execute.
225 * Attach a function to be executed before an AJAX request is send.
227 * The XMLHttpRequest and settings used for that request are passed
228 * as arguments to the callback.
230 * @example $("#msg").ajaxSend(function(request, settings){
231 * $(this).append("<li>Starting request at " + settings.url + "</li>");
233 * @desc Show a message before an AJAX request is send.
237 * @param Function callback The function to execute.
242 var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(",");
244 for ( var i = 0; i < e.length; i++ ) new function(){
246 jQuery.fn[o] = function(f){
247 return this.bind(o, f);
255 * Load a remote page using an HTTP GET request.
257 * @example $.get("test.cgi");
259 * @example $.get("test.cgi", { name: "John", time: "2pm" } );
261 * @example $.get("test.cgi", function(data){
262 * alert("Data Loaded: " + data);
265 * @example $.get("test.cgi",
266 * { name: "John", time: "2pm" },
268 * alert("Data Loaded: " + data);
273 * @type XMLHttpRequest
274 * @param String url The URL of the page to load.
275 * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
276 * @param Function callback (optional) A function to be executed whenever the data is loaded.
279 get: function( url, data, callback, type, ifModified ) {
280 // shift arguments if data argument was ommited
281 if ( data && data.constructor == Function ) {
290 ifModified: ifModified
295 * Load a remote page using an HTTP GET request, only if it hasn't
296 * been modified since it was last retrieved.
298 * @example $.getIfModified("test.html");
300 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } );
302 * @example $.getIfModified("test.cgi", function(data){
303 * alert("Data Loaded: " + data);
306 * @example $.getifModified("test.cgi",
307 * { name: "John", time: "2pm" },
309 * alert("Data Loaded: " + data);
313 * @name $.getIfModified
314 * @type XMLHttpRequest
315 * @param String url The URL of the page to load.
316 * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
317 * @param Function callback (optional) A function to be executed whenever the data is loaded.
320 getIfModified: function( url, data, callback, type ) {
321 return jQuery.get(url, data, callback, type, 1);
325 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
327 * Warning: Safari <= 2.0.x is unable to evalulate scripts in a global
328 * context synchronously. If you load functions via getScript, make sure
329 * to call them after a delay.
331 * @example $.getScript("test.js");
333 * @example $.getScript("test.js", function(){
334 * alert("Script loaded and executed.");
338 * @type XMLHttpRequest
339 * @param String url The URL of the page to load.
340 * @param Function callback (optional) A function to be executed whenever the data is loaded.
343 getScript: function( url, callback ) {
344 return jQuery.get(url, null, callback, "script");
348 * Load JSON data using an HTTP GET request.
350 * @example $.getJSON("test.js", function(json){
351 * alert("JSON Data: " + json.users[3].name);
354 * @example $.getJSON("test.js",
355 * { name: "John", time: "2pm" },
357 * alert("JSON Data: " + json.users[3].name);
362 * @type XMLHttpRequest
363 * @param String url The URL of the page to load.
364 * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
365 * @param Function callback A function to be executed whenever the data is loaded.
368 getJSON: function( url, data, callback ) {
369 return jQuery.get(url, data, callback, "json");
373 * Load a remote page using an HTTP POST request.
375 * @example $.post("test.cgi");
377 * @example $.post("test.cgi", { name: "John", time: "2pm" } );
379 * @example $.post("test.cgi", function(data){
380 * alert("Data Loaded: " + data);
383 * @example $.post("test.cgi",
384 * { name: "John", time: "2pm" },
386 * alert("Data Loaded: " + data);
391 * @type XMLHttpRequest
392 * @param String url The URL of the page to load.
393 * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
394 * @param Function callback (optional) A function to be executed whenever the data is loaded.
397 post: function( url, data, callback, type ) {
411 * Set the timeout of all AJAX requests to a specific amount of time.
412 * This will make all future AJAX requests timeout after a specified amount
415 * Set to null or 0 to disable timeouts (default).
417 * You can manually abort requests with the XMLHttpRequest's (returned by
418 * all ajax functions) abort() method.
420 * @example $.ajaxTimeout( 5000 );
421 * @desc Make all AJAX requests timeout after 5 seconds.
423 * @name $.ajaxTimeout
425 * @param Number time How long before an AJAX request times out.
428 ajaxTimeout: function(timeout) {
429 jQuery.timeout = timeout;
432 // Last-Modified header cache for next request
436 * Load a remote page using an HTTP request.
438 * This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for
439 * higher-level abstractions.
441 * $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't
442 * need that object to manipulate directly, but it is available if you need to
443 * abort the request manually.
445 * Note: Make sure the server sends the right mimetype (eg. xml as
446 * "text/xml"). Sending the wrong mimetype will get you into serious
447 * trouble that jQuery can't solve.
449 * Supported datatypes are (see dataType option):
451 * "xml": Returns a XML document that can be processed via jQuery.
453 * "html": Returns HTML as plain text, included script tags are evaluated.
455 * "script": Evaluates the response as Javascript and returns it as plain text.
457 * "json": Evaluates the response as JSON and returns a Javascript Object
459 * $.ajax() takes one argument, an object of key/value pairs, that are
460 * used to initalize and handle the request. These are all the key/values that can
463 * (String) url - The URL to request.
465 * (String) type - The type of request to make ("POST" or "GET"), default is "GET".
467 * (String) dataType - The type of data that you're expecting back from
468 * the server. No default: If the server sends xml, the responseXML, otherwise
469 * the responseText is passed to the success callback.
471 * (Boolean) ifModified - Allow the request to be successful only if the
472 * response has changed since the last request. This is done by checking the
473 * Last-Modified header. Default value is false, ignoring the header.
475 * (Number) timeout - Local timeout to override global timeout, eg. to give a
476 * single request a longer timeout while all others timeout after 1 seconds.
477 * See $.ajaxTimeout() for global timeouts.
479 * (Boolean) global - Whether to trigger global AJAX event handlers for
480 * this request, default is true. Set to false to prevent that global handlers
481 * like ajaxStart or ajaxStop are triggered.
483 * (Function) error - A function to be called if the request fails. The
484 * function gets passed tree arguments: The XMLHttpRequest object, a
485 * string describing the type of error that occurred and an optional
486 * exception object, if one occured.
488 * (Function) success - A function to be called if the request succeeds. The
489 * function gets passed one argument: The data returned from the server,
490 * formatted according to the 'dataType' parameter.
492 * (Function) complete - A function to be called when the request finishes. The
493 * function gets passed two arguments: The XMLHttpRequest object and a
494 * string describing the type of success of the request.
496 * (Object|String) data - Data to be sent to the server. Converted to a query
497 * string, if not already a string. Is appended to the url for GET-requests.
498 * See processData option to prevent this automatic processing.
500 * (String) contentType - When sending data to the server, use this content-type.
501 * Default is "application/x-www-form-urlencoded", which is fine for most cases.
503 * (Boolean) processData - By default, data passed in to the data option as an object
504 * other as string will be processed and transformed into a query string, fitting to
505 * the default content-type "application/x-www-form-urlencoded". If you want to send
506 * DOMDocuments, set this option to false.
508 * (Boolean) async - By default, all requests are send asynchronous (set to true).
509 * If you need synchronous requests, set this option to false.
511 * (Function) beforeSend - A pre-callback to set custom headers etc., the
512 * XMLHttpRequest is passed as the only argument.
519 * @desc Load and execute a JavaScript file.
524 * data: "name=John&location=Boston",
525 * success: function(msg){
526 * alert( "Data Saved: " + msg );
529 * @desc Save some data to the server and notify the user once its complete.
531 * @example var html = $.ajax({
535 * @desc Loads data synchronously. Blocks the browser while the requests is active.
536 * It is better to block user interaction with others means when synchronization is
537 * necessary, instead to block the complete browser.
539 * @example var xmlDocument = [create xml document];
542 * processData: false,
544 * success: handleResponse
546 * @desc Sends an xml document as data to the server. By setting the processData
547 * option to false, the automatic conversion of data to strings is prevented.
550 * @type XMLHttpRequest
551 * @param Hash prop A set of properties to initialize the request with.
554 ajax: function( s ) {
555 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
560 timeout: jQuery.timeout,
567 contentType: "application/x-www-form-urlencoded",
575 // convert data if not already a string
576 if (s.processData && typeof s.data != 'string')
577 s.data = jQuery.param(s.data);
578 // append data to url for get requests
579 if( s.type.toLowerCase() == "get" )
580 // "?" + data or "&" + data (in case there are already params)
581 s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data;
584 // Watch for a new set of requests
585 if ( s.global && ! jQuery.active++ )
586 jQuery.event.trigger( "ajaxStart" );
588 var requestDone = false;
590 // Create the request object
591 var xml = new XMLHttpRequest();
594 xml.open(s.type, s.url, s.async);
596 // Set the correct header, if data is being sent
598 xml.setRequestHeader("Content-Type", s.contentType);
600 // Set the If-Modified-Since header, if ifModified mode.
602 xml.setRequestHeader("If-Modified-Since",
603 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
605 // Set header so the called script knows that it's an XMLHttpRequest
606 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
608 // Make sure the browser sends the right content length
609 if ( xml.overrideMimeType )
610 xml.setRequestHeader("Connection", "close");
612 // Allow custom headers/mimetypes
616 jQuery.event.trigger("ajaxSend", [xml, s]);
618 // Wait for a response to come back
619 var onreadystatechange = function(isTimeout){
620 // The transfer is complete and the data is available, or the request timed out
621 if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
625 status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
626 s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
627 // Make sure that the request was successful or notmodified
628 if ( status != "error" ) {
629 // Cache Last-Modified header, if ifModified mode.
632 modRes = xml.getResponseHeader("Last-Modified");
633 } catch(e) {} // swallow exception thrown by FF if header is not available
635 if ( s.ifModified && modRes )
636 jQuery.lastModified[s.url] = modRes;
638 // process the data (runs the xml through httpData regardless of callback)
639 var data = jQuery.httpData( xml, s.dataType );
641 // If a local callback was specified, fire it and pass it the data
643 s.success( data, status );
645 // Fire the global callback
647 jQuery.event.trigger( "ajaxSuccess", [xml, s] );
651 jQuery.handleError(s, xml, status, e);
654 // The request was completed
656 jQuery.event.trigger( "ajaxComplete", [xml, s] );
658 // Handle the global AJAX counter
659 if ( s.global && ! --jQuery.active )
660 jQuery.event.trigger( "ajaxStop" );
663 if ( s.complete ) s.complete(xml, status);
666 xml.onreadystatechange = function(){};
670 xml.onreadystatechange = onreadystatechange;
674 setTimeout(function(){
675 // Check to see if the request is still happening
677 // Cancel the request
680 if ( !requestDone ) onreadystatechange( "timeout" );
687 // save non-leaking reference
694 jQuery.handleError(s, xml, null, e);
697 // return XMLHttpRequest to allow aborting the request etc.
701 handleError: function(s, xml, status, e) {
702 // If a local callback was specified, fire it
703 if ( s.error ) s.error( xml, status, e );
705 // Fire the global callback
707 jQuery.event.trigger( "ajaxError", [xml, s, e] );
710 // Counter for holding the number of active queries
713 // Determines if an XMLHttpRequest was successful or not
714 httpSuccess: function(r) {
715 return !r.status && location.protocol == "file:" ||
716 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
717 jQuery.browser.safari && r.status == undefined;
720 // Determines if an XMLHttpRequest returns NotModified
721 httpNotModified: function(xml, url) {
722 var xmlRes = xml.getResponseHeader("Last-Modified");
724 // Firefox always returns 200. check Last-Modified date
725 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
726 jQuery.browser.safari && xml.status == undefined;
729 /* Get the data out of an XMLHttpRequest.
730 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
731 * otherwise return plain text.
732 * (String) data - The type of data that you're expecting back,
733 * (e.g. "xml", "html", "script")
735 httpData: function(r,type) {
736 var ct = r.getResponseHeader("content-type");
737 var data = !type && ct && ct.indexOf("xml") >= 0;
738 data = type == "xml" || data ? r.responseXML : r.responseText;
740 // If the type is "script", eval it in global context
741 if ( type == "script" ) {
742 jQuery.globalEval( data );
745 // Get the JavaScript object, if JSON is used.
746 if ( type == "json" ) eval( "data = " + data );
748 // evaluate scripts within html
749 if ( type == "html" ) jQuery("<div>").html(data).evalScripts();
754 // Serialize an array of form elements or a set of
755 // key/values into a query string
759 // If an array was passed in, assume that it is an array
761 if ( a.constructor == Array || a.jquery ) {
762 // Serialize the form elements
763 for ( var i = 0; i < a.length; i++ )
764 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
766 // Otherwise, assume that it's an object of key/value pairs
768 // Serialize the key/values
770 // If the value is an array then the key names need to be repeated
771 if( a[j].constructor == Array ) {
772 for (var k = 0; k < a[j].length; k++) {
773 s.push( j + "=" + encodeURIComponent( a[j][k] ) );
776 s.push( j + "=" + encodeURIComponent( a[j] ) );
781 // Return the resulting serialization
785 // evalulates a script in global context
786 // not reliable for safari
787 globalEval: function(data) {
788 if (window.execScript)
789 window.execScript( data );
790 else if(jQuery.browser.safari)
791 // safari doesn't provide a synchronous global eval
792 window.setTimeout( data, 0 );
794 eval.call( window, data );