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 * Note: Avoid to use this to load scripts, instead use $.getScript.
27 * @example $("#feeds").load("feeds.html");
28 * @before <div id="feeds"></div>
29 * @result <div id="feeds"><b>45</b> feeds found.</div>
31 * @example $("#feeds").load("feeds.html",
33 * function() { alert("The last 25 entries in the feed have been loaded"); }
35 * @desc Same as above, but with an additional parameter
36 * and a callback that is executed when the data was loaded.
40 * @param String url The URL of the HTML file to load.
41 * @param Object params (optional) A set of key/value pairs that will be sent as data to the server.
42 * @param Function callback (optional) A function to be executed whenever the data is loaded (parameters: responseText, status and response itself).
45 load: function( url, params, callback, ifModified ) {
46 if ( url.constructor == Function )
47 return this.bind("load", url);
49 callback = callback || function(){};
51 // Default to a GET request
54 // If the second parameter was provided
57 if ( params.constructor == Function ) {
58 // We assume that it's the callback
62 // Otherwise, build a param string
64 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.html(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 || "" );
135 // If IE is used, create a wrapper for the XMLHttpRequest object
136 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
137 XMLHttpRequest = function(){
138 return new ActiveXObject("Microsoft.XMLHTTP");
141 // Attach a bunch of functions for handling common AJAX events
144 * Attach a function to be executed whenever an AJAX request begins
145 * and there is none already active.
147 * @example $("#loading").ajaxStart(function(){
150 * @desc Show a loading message whenever an AJAX request starts
151 * (and none is already active).
155 * @param Function callback The function to execute.
160 * Attach a function to be executed whenever all AJAX requests have ended.
162 * @example $("#loading").ajaxStop(function(){
165 * @desc Hide a loading message after all the AJAX requests have stopped.
169 * @param Function callback The function to execute.
174 * Attach a function to be executed whenever an AJAX request completes.
176 * The XMLHttpRequest and settings used for that request are passed
177 * as arguments to the callback.
179 * @example $("#msg").ajaxComplete(function(request, settings){
180 * $(this).append("<li>Request Complete.</li>");
182 * @desc Show a message when an AJAX request completes.
186 * @param Function callback The function to execute.
191 * Attach a function to be executed whenever an AJAX request completes
194 * The XMLHttpRequest and settings used for that request are passed
195 * as arguments to the callback.
197 * @example $("#msg").ajaxSuccess(function(request, settings){
198 * $(this).append("<li>Successful Request!</li>");
200 * @desc Show a message when an AJAX request completes successfully.
204 * @param Function callback The function to execute.
209 * Attach a function to be executed whenever an AJAX request fails.
211 * The XMLHttpRequest and settings used for that request are passed
212 * as arguments to the callback. A third argument, an exception object,
213 * is passed if an exception occured while processing the request.
215 * @example $("#msg").ajaxError(function(request, settings){
216 * $(this).append("<li>Error requesting page " + settings.url + "</li>");
218 * @desc Show a message when an AJAX request fails.
222 * @param Function callback The function to execute.
227 * Attach a function to be executed before an AJAX request is send.
229 * The XMLHttpRequest and settings used for that request are passed
230 * as arguments to the callback.
232 * @example $("#msg").ajaxSend(function(request, settings){
233 * $(this).append("<li>Starting request at " + settings.url + "</li>");
235 * @desc Show a message before an AJAX request is send.
239 * @param Function callback The function to execute.
244 var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(",");
246 for ( var i = 0; i < e.length; i++ ) new function(){
248 jQuery.fn[o] = function(f){
249 return this.bind(o, f);
257 * Load a remote page using an HTTP GET request.
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 Hash params (optional) A set of 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.
281 get: function( url, data, callback, type, ifModified ) {
282 // shift arguments if data argument was ommited
283 if ( data && data.constructor == Function ) {
292 ifModified: ifModified
297 * Load a remote page using an HTTP GET request, only if it hasn't
298 * been modified since it was last retrieved.
300 * @example $.getIfModified("test.html");
302 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } );
304 * @example $.getIfModified("test.cgi", function(data){
305 * alert("Data Loaded: " + data);
308 * @example $.getifModified("test.cgi",
309 * { name: "John", time: "2pm" },
311 * alert("Data Loaded: " + data);
315 * @name $.getIfModified
316 * @type XMLHttpRequest
317 * @param String url The URL of the page to load.
318 * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
319 * @param Function callback (optional) A function to be executed whenever the data is loaded.
322 getIfModified: function( url, data, callback, type ) {
323 return jQuery.get(url, data, callback, type, 1);
327 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
329 * Warning: Safari <= 2.0.x is unable to evalulate scripts in a global
330 * context synchronously. If you load functions via getScript, make sure
331 * to call them after a delay.
333 * @example $.getScript("test.js");
335 * @example $.getScript("test.js", function(){
336 * alert("Script loaded and executed.");
340 * @type XMLHttpRequest
341 * @param String url The URL of the page to load.
342 * @param Function callback (optional) A function to be executed whenever the data is loaded.
345 getScript: function( url, callback ) {
346 return jQuery.get(url, null, callback, "script");
350 * Load JSON data using an HTTP GET request.
352 * @example $.getJSON("test.js", function(json){
353 * alert("JSON Data: " + json.users[3].name);
356 * @example $.getJSON("test.js",
357 * { name: "John", time: "2pm" },
359 * alert("JSON Data: " + json.users[3].name);
364 * @type XMLHttpRequest
365 * @param String url The URL of the page to load.
366 * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
367 * @param Function callback A function to be executed whenever the data is loaded.
370 getJSON: function( url, data, callback ) {
371 return jQuery.get(url, data, callback, "json");
375 * Load a remote page using an HTTP POST request.
377 * @example $.post("test.cgi");
379 * @example $.post("test.cgi", { name: "John", time: "2pm" } );
381 * @example $.post("test.cgi", function(data){
382 * alert("Data Loaded: " + data);
385 * @example $.post("test.cgi",
386 * { name: "John", time: "2pm" },
388 * alert("Data Loaded: " + data);
393 * @type XMLHttpRequest
394 * @param String url The URL of the page to load.
395 * @param Hash params (optional) A set of key/value pairs that will be sent to the server.
396 * @param Function callback (optional) A function to be executed whenever the data is loaded.
399 post: function( url, data, callback, type ) {
413 * Set the timeout of all AJAX requests to a specific amount of time.
414 * This will make all future AJAX requests timeout after a specified amount
417 * Set to null or 0 to disable timeouts (default).
419 * You can manually abort requests with the XMLHttpRequest's (returned by
420 * all ajax functions) abort() method.
422 * @example $.ajaxTimeout( 5000 );
423 * @desc Make all AJAX requests timeout after 5 seconds.
425 * @name $.ajaxTimeout
427 * @param Number time How long before an AJAX request times out.
430 ajaxTimeout: function(timeout) {
431 jQuery.timeout = timeout;
434 // Last-Modified header cache for next request
438 * Load a remote page using an HTTP request.
440 * This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for
441 * higher-level abstractions.
443 * $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't
444 * need that object to manipulate directly, but it is available if you need to
445 * abort the request manually.
447 * Note: Make sure the server sends the right mimetype (eg. xml as
448 * "text/xml"). Sending the wrong mimetype will get you into serious
449 * trouble that jQuery can't solve.
451 * Supported datatypes are (see dataType option):
453 * "xml": Returns a XML document that can be processed via jQuery.
455 * "html": Returns HTML as plain text, included script tags are evaluated.
457 * "script": Evaluates the response as Javascript and returns it as plain text.
459 * "json": Evaluates the response as JSON and returns a Javascript Object
461 * $.ajax() takes one argument, an object of key/value pairs, that are
462 * used to initalize and handle the request. These are all the key/values that can
465 * (String) url - The URL to request.
467 * (String) type - The type of request to make ("POST" or "GET"), default is "GET".
469 * (String) dataType - The type of data that you're expecting back from
470 * the server. No default: If the server sends xml, the responseXML, otherwise
471 * the responseText is passed to the success callback.
473 * (Boolean) ifModified - Allow the request to be successful only if the
474 * response has changed since the last request. This is done by checking the
475 * Last-Modified header. Default value is false, ignoring the header.
477 * (Number) timeout - Local timeout to override global timeout, eg. to give a
478 * single request a longer timeout while all others timeout after 1 second.
479 * See $.ajaxTimeout() for global timeouts.
481 * (Boolean) global - Whether to trigger global AJAX event handlers for
482 * this request, default is true. Set to false to prevent that global handlers
483 * like ajaxStart or ajaxStop are triggered.
485 * (Function) error - A function to be called if the request fails. The
486 * function gets passed tree arguments: The XMLHttpRequest object, a
487 * string describing the type of error that occurred and an optional
488 * exception object, if one occured.
490 * (Function) success - A function to be called if the request succeeds. The
491 * function gets passed one argument: The data returned from the server,
492 * formatted according to the 'dataType' parameter.
494 * (Function) complete - A function to be called when the request finishes. The
495 * function gets passed two arguments: The XMLHttpRequest object and a
496 * string describing the type of success of the request.
498 * (Object|String) data - Data to be sent to the server. Converted to a query
499 * string, if not already a string. Is appended to the url for GET-requests.
500 * See processData option to prevent this automatic processing.
502 * (String) contentType - When sending data to the server, use this content-type.
503 * Default is "application/x-www-form-urlencoded", which is fine for most cases.
505 * (Boolean) processData - By default, data passed in to the data option as an object
506 * other as string will be processed and transformed into a query string, fitting to
507 * the default content-type "application/x-www-form-urlencoded". If you want to send
508 * DOMDocuments, set this option to false.
510 * (Boolean) async - By default, all requests are send asynchronous (set to true).
511 * If you need synchronous requests, set this option to false.
513 * (Function) beforeSend - A pre-callback to set custom headers etc., the
514 * XMLHttpRequest is passed as the only argument.
521 * @desc Load and execute a JavaScript file.
526 * data: "name=John&location=Boston",
527 * success: function(msg){
528 * alert( "Data Saved: " + msg );
531 * @desc Save some data to the server and notify the user once its complete.
533 * @example var html = $.ajax({
537 * @desc Loads data synchronously. Blocks the browser while the requests is active.
538 * It is better to block user interaction with others means when synchronization is
539 * necessary, instead to block the complete browser.
541 * @example var xmlDocument = [create xml document];
544 * processData: false,
546 * success: handleResponse
548 * @desc Sends an xml document as data to the server. By setting the processData
549 * option to false, the automatic conversion of data to strings is prevented.
552 * @type XMLHttpRequest
553 * @param Hash prop A set of properties to initialize the request with.
556 ajax: function( s ) {
557 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
562 timeout: jQuery.timeout,
569 contentType: "application/x-www-form-urlencoded",
577 // convert data if not already a string
578 if (s.processData && typeof s.data != 'string')
579 s.data = jQuery.param(s.data);
580 // append data to url for get requests
581 if( s.type.toLowerCase() == "get" )
582 // "?" + data or "&" + data (in case there are already params)
583 s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data;
586 // Watch for a new set of requests
587 if ( s.global && ! jQuery.active++ )
588 jQuery.event.trigger( "ajaxStart" );
590 var requestDone = false;
592 // Create the request object
593 var xml = new XMLHttpRequest();
596 xml.open(s.type, s.url, s.async);
598 // Set the correct header, if data is being sent
600 xml.setRequestHeader("Content-Type", s.contentType);
602 // Set the If-Modified-Since header, if ifModified mode.
604 xml.setRequestHeader("If-Modified-Since",
605 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
607 // Set header so the called script knows that it's an XMLHttpRequest
608 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
610 // Make sure the browser sends the right content length
611 if ( xml.overrideMimeType )
612 xml.setRequestHeader("Connection", "close");
614 // Allow custom headers/mimetypes
618 jQuery.event.trigger("ajaxSend", [xml, s]);
620 // Wait for a response to come back
621 var onreadystatechange = function(isTimeout){
622 // The transfer is complete and the data is available, or the request timed out
623 if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
627 status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
628 s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
629 // Make sure that the request was successful or notmodified
630 if ( status != "error" ) {
631 // Cache Last-Modified header, if ifModified mode.
634 modRes = xml.getResponseHeader("Last-Modified");
635 } catch(e) {} // swallow exception thrown by FF if header is not available
637 if ( s.ifModified && modRes )
638 jQuery.lastModified[s.url] = modRes;
640 // process the data (runs the xml through httpData regardless of callback)
641 var data = jQuery.httpData( xml, s.dataType );
643 // If a local callback was specified, fire it and pass it the data
645 s.success( data, status );
647 // Fire the global callback
649 jQuery.event.trigger( "ajaxSuccess", [xml, s] );
651 jQuery.handleError(s, xml, status);
655 jQuery.handleError(s, xml, status, e);
658 // The request was completed
660 jQuery.event.trigger( "ajaxComplete", [xml, s] );
662 // Handle the global AJAX counter
663 if ( s.global && ! --jQuery.active )
664 jQuery.event.trigger( "ajaxStop" );
667 if ( s.complete ) s.complete(xml, status);
670 xml.onreadystatechange = function(){};
674 xml.onreadystatechange = onreadystatechange;
678 setTimeout(function(){
679 // Check to see if the request is still happening
681 // Cancel the request
684 if ( !requestDone ) onreadystatechange( "timeout" );
691 // save non-leaking reference
698 jQuery.handleError(s, xml, null, e);
701 // return XMLHttpRequest to allow aborting the request etc.
705 handleError: function(s, xml, status, e) {
706 // If a local callback was specified, fire it
707 if ( s.error ) s.error( xml, status, e );
709 // Fire the global callback
711 jQuery.event.trigger( "ajaxError", [xml, s, e] );
714 // Counter for holding the number of active queries
717 // Determines if an XMLHttpRequest was successful or not
718 httpSuccess: function(r) {
720 return !r.status && location.protocol == "file:" ||
721 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
722 jQuery.browser.safari && r.status == undefined;
727 // Determines if an XMLHttpRequest returns NotModified
728 httpNotModified: function(xml, url) {
730 var xmlRes = xml.getResponseHeader("Last-Modified");
732 // Firefox always returns 200. check Last-Modified date
733 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
734 jQuery.browser.safari && xml.status == undefined;
739 /* Get the data out of an XMLHttpRequest.
740 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
741 * otherwise return plain text.
742 * (String) data - The type of data that you're expecting back,
743 * (e.g. "xml", "html", "script")
745 httpData: function(r,type) {
746 var ct = r.getResponseHeader("content-type");
747 var data = !type && ct && ct.indexOf("xml") >= 0;
748 data = type == "xml" || data ? r.responseXML : r.responseText;
750 // If the type is "script", eval it in global context
751 if ( type == "script" ) {
752 jQuery.globalEval( data );
755 // Get the JavaScript object, if JSON is used.
756 if ( type == "json" ) eval( "data = " + data );
758 // evaluate scripts within html
759 if ( type == "html" ) jQuery("<div>").html(data).evalScripts();
764 // Serialize an array of form elements or a set of
765 // key/values into a query string
769 // If an array was passed in, assume that it is an array
771 if ( a.constructor == Array || a.jquery ) {
772 // Serialize the form elements
773 for ( var i = 0; i < a.length; i++ )
774 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
776 // Otherwise, assume that it's an object of key/value pairs
778 // Serialize the key/values
780 // If the value is an array then the key names need to be repeated
781 if( a[j].constructor == Array ) {
782 for (var k = 0; k < a[j].length; k++) {
783 s.push( j + "=" + encodeURIComponent( a[j][k] ) );
786 s.push( j + "=" + encodeURIComponent( a[j] ) );
791 // Return the resulting serialization
795 // evalulates a script in global context
796 // not reliable for safari
797 globalEval: function(data) {
798 if (window.execScript)
799 window.execScript( data );
800 else if(jQuery.browser.safari)
801 // safari doesn't provide a synchronous global eval
802 window.setTimeout( data, 0 );
804 eval.call( window, data );