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 A set of key/value pairs that will be sent to the server.
15 * @param Function callback A function to be executed whenever the data is loaded.
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("load is done"); }
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 A set of key/value pairs that will be sent as data to the server.
40 * @param Function callback A function to be executed whenever the data is loaded (parameters: responseText, status and reponse 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. If you need
93 * serialization similar to the form submit of a browser,
94 * you should use the form plugin. This is also true for
95 * selects with multiple attribute set, 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 // for some weird reason, it doesn't work if the callback is ommited
125 jQuery.getScript( this.src );
127 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(
138 navigator.userAgent.indexOf("MSIE 5") >= 0 ?
139 "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
143 // Attach a bunch of functions for handling common AJAX events
146 * Attach a function to be executed whenever an AJAX request begins.
148 * @example $("#loading").ajaxStart(function(){
151 * @desc Show a loading message whenever an AJAX request starts.
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 * @example $("#msg").ajaxComplete(function(){
177 * $(this).append("<li>Request Complete.</li>");
179 * @desc Show a message when an AJAX request completes.
183 * @param Function callback The function to execute.
188 * Attach a function to be executed whenever an AJAX request completes
191 * @example $("#msg").ajaxSuccess(function(){
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 * @example $("#msg").ajaxError(function(){
206 * $(this).append("<li>Error requesting page.</li>");
208 * @desc Show a message when an AJAX request fails.
212 * @param Function callback The function to execute.
217 var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(",");
219 for ( var i = 0; i < e.length; i++ ) new function(){
221 jQuery.fn[o] = function(f){
222 return this.bind(o, f);
230 * Load a remote page using an HTTP GET request. All of the arguments to
231 * the method (except URL) are optional.
233 * @example $.get("test.cgi")
235 * @example $.get("test.cgi", { name: "John", time: "2pm" } )
237 * @example $.get("test.cgi", function(data){
238 * alert("Data Loaded: " + data);
241 * @example $.get("test.cgi",
242 * { name: "John", time: "2pm" },
244 * alert("Data Loaded: " + data);
250 * @param String url The URL of the page to load.
251 * @param Hash params A set of key/value pairs that will be sent to the server.
252 * @param Function callback A function to be executed whenever the data is loaded.
255 get: function( url, data, callback, type, ifModified ) {
256 // shift arguments if data argument was ommited
257 if ( data && data.constructor == Function ) {
268 ifModified: ifModified
273 * Load a remote page using an HTTP GET request, only if it hasn't
274 * been modified since it was last retrieved. All of the arguments to
275 * the method (except URL) are optional.
277 * @example $.getIfModified("test.html")
279 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } )
281 * @example $.getIfModified("test.cgi", function(data){
282 * alert("Data Loaded: " + data);
285 * @example $.getifModified("test.cgi",
286 * { name: "John", time: "2pm" },
288 * alert("Data Loaded: " + data);
292 * @name $.getIfModified
294 * @param String url The URL of the page to load.
295 * @param Hash params A set of key/value pairs that will be sent to the server.
296 * @param Function callback A function to be executed whenever the data is loaded.
299 getIfModified: function( url, data, callback, type ) {
300 jQuery.get(url, data, callback, type, 1);
304 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
305 * All of the arguments to the method (except URL) are optional.
307 * Warning: Safari <= 2.0.x is unable to evalulate scripts in a global
308 * context sychronously. If you load functions via getScript, make sure
309 * to call them after a delay.
311 * @example $.getScript("test.js")
313 * @example $.getScript("test.js", function(){
314 * alert("Script loaded and executed.");
319 * @param String url The URL of the page to load.
320 * @param Function callback A function to be executed whenever the data is loaded.
323 getScript: function( url, callback ) {
325 jQuery.get(url, null, callback, "script");
327 jQuery.get(url, null, null, "script");
332 * Load a remote JSON object using an HTTP GET request.
333 * All of the arguments to the method (except URL) are optional.
335 * @example $.getJSON("test.js", function(json){
336 * alert("JSON Data: " + json.users[3].name);
339 * @example $.getJSON("test.js",
340 * { name: "John", time: "2pm" },
342 * alert("JSON Data: " + json.users[3].name);
348 * @param String url The URL of the page to load.
349 * @param Hash params A set of key/value pairs that will be sent to the server.
350 * @param Function callback A function to be executed whenever the data is loaded.
353 getJSON: function( url, data, callback ) {
354 jQuery.get(url, data, callback, "json");
358 * Load a remote page using an HTTP POST request. All of the arguments to
359 * the method (except URL) are optional.
361 * @example $.post("test.cgi")
363 * @example $.post("test.cgi", { name: "John", time: "2pm" } )
365 * @example $.post("test.cgi", function(data){
366 * alert("Data Loaded: " + data);
369 * @example $.post("test.cgi",
370 * { name: "John", time: "2pm" },
372 * alert("Data Loaded: " + data);
378 * @param String url The URL of the page to load.
379 * @param Hash params A set of key/value pairs that will be sent to the server.
380 * @param Function callback A function to be executed whenever the data is loaded.
383 post: function( url, data, callback, type ) {
398 * Set the timeout of all AJAX requests to a specific amount of time.
399 * This will make all future AJAX requests timeout after a specified amount
400 * of time (the default is no timeout).
402 * @example $.ajaxTimeout( 5000 );
403 * @desc Make all AJAX requests timeout after 5 seconds.
405 * @name $.ajaxTimeout
407 * @param Number time How long before an AJAX request times out.
410 ajaxTimeout: function(timeout) {
411 jQuery.timeout = timeout;
414 // Last-Modified header cache for next request
418 * Load a remote page using an HTTP request. This function is the primary
419 * means of making AJAX requests using jQuery.
421 * $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't
422 * need that object to manipulate directly, but it is available if you need to
423 * abort the request manually.
425 * Please note: Make sure the server sends the right mimetype (eg. xml as
426 * "text/xml"). Sending the wrong mimetype will get you into serious
427 * trouble that jQuery can't solve.
429 * Supported datatypes (see dataType option) are:
431 * "xml": Returns a XML document that can be processed via jQuery.
433 * "html": Returns HTML as plain text, included script tags are evaluated.
435 * "script": Evaluates the response as Javascript and returns it as plain text.
437 * "json": Evaluates the response as JSON and returns a Javascript Object
439 * $.ajax() takes one property, an object of key/value pairs, that are
440 * used to initalize the request. These are all the key/values that can
441 * be passed in to 'prop':
443 * (String) url - The URL of the page to request.
445 * (String) type - The type of request to make (e.g. "POST" or "GET"), default is "GET".
447 * (String) dataType - The type of data that you're expecting back from
448 * the server. No default: If the server sends xml, the responseXML, otherwise
449 * the responseText is is passed to the success callback.
451 * (Boolean) ifModified - Allow the request to be successful only if the
452 * response has changed since the last request, default is false, ignoring
453 * the Last-Modified header
455 * (Number) timeout - Local timeout to override global timeout, eg. to give a
456 * single request a longer timeout while all others timeout after 1 seconds,
457 * see $.ajaxTimeout()
459 * (Boolean) global - Wheather to trigger global AJAX event handlers for
460 * this request, default is true. Set to false to prevent that global handlers
461 * like ajaxStart or ajaxStop are triggered.
463 * (Function) error - A function to be called if the request fails. The
464 * function gets passed two arguments: The XMLHttpRequest object and a
465 * string describing the type of error that occurred.
467 * (Function) success - A function to be called if the request succeeds. The
468 * function gets passed one argument: The data returned from the server,
469 * formatted according to the 'dataType' parameter.
471 * (Function) complete - A function to be called when the request finishes. The
472 * function gets passed two arguments: The XMLHttpRequest object and a
473 * string describing the type the success of the request.
475 * (Object|String) data - Data to be sent to the server. Converted to a query
476 * string, if not already a string. Is appended to the url for GET-requests.
477 * Override processData option to prevent processing.
479 * (String) contentType - When sending data to the server, use this content-type,
480 * default is "application/x-www-form-urlencoded", which is fine for most cases.
482 * (Boolean) processData - By default, data passed in as an object other as string
483 * will be processed and transformed into a query string, fitting to the default
484 * content-type "application/x-www-form-urlencoded". If you want to send DOMDocuments,
485 * set this option to false.
487 * (Boolean) async - By default, all requests are send asynchronous (set to true).
488 * If you need synchronous requests, set this option to false.
495 * @desc Load and execute a JavaScript file.
500 * data: "name=John&location=Boston",
501 * success: function(msg){
502 * alert( "Data Saved: " + msg );
505 * @desc Save some data to the server and notify the user once its complete.
508 * @type XMLHttpRequest
509 * @param Hash prop A set of properties to initialize the request with.
512 ajax: function( s ) {
513 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
518 timeout: jQuery.timeout,
525 contentType: "application/x-www-form-urlencoded",
532 // convert data if not already a string
533 if (s.processData && typeof s.data != 'string')
534 s.data = jQuery.param(s.data);
535 // append data to url for get requests
536 if( s.type.toLowerCase() == "get" )
537 // "?" + data or "&" + data (in case there are already params)
538 s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data;
541 // Watch for a new set of requests
542 if ( s.global && ! jQuery.active++ )
543 jQuery.event.trigger( "ajaxStart" );
545 var requestDone = false;
547 // Create the request object
548 var xml = new XMLHttpRequest();
551 xml.open(s.type, s.url, s.async);
553 // Set the correct header, if data is being sent
555 xml.setRequestHeader("Content-Type", s.contentType);
557 // Set the If-Modified-Since header, if ifModified mode.
559 xml.setRequestHeader("If-Modified-Since",
560 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
562 // Set header so the called script knows that it's an XMLHttpRequest
563 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
565 // Make sure the browser sends the right content length
566 if ( xml.overrideMimeType )
567 xml.setRequestHeader("Connection", "close");
569 // Wait for a response to come back
570 var onreadystatechange = function(isTimeout){
571 // The transfer is complete and the data is available, or the request timed out
572 if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
575 var status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
576 s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
578 // Make sure that the request was successful or notmodified
579 if ( status != "error" ) {
580 // Cache Last-Modified header, if ifModified mode.
583 modRes = xml.getResponseHeader("Last-Modified");
584 } catch(e) {} // swallow exception thrown by FF if header is not available
586 if ( s.ifModified && modRes )
587 jQuery.lastModified[s.url] = modRes;
589 // process the data (runs the xml through httpData regardless of callback)
590 var data = jQuery.httpData( xml, s.dataType );
592 // If a local callback was specified, fire it and pass it the data
594 s.success( data, status );
596 // Fire the global callback
598 jQuery.event.trigger( "ajaxSuccess" );
600 // Otherwise, the request was not successful
602 // If a local callback was specified, fire it
603 if ( s.error ) s.error( xml, status );
605 // Fire the global callback
607 jQuery.event.trigger( "ajaxError" );
610 // The request was completed
612 jQuery.event.trigger( "ajaxComplete" );
614 // Handle the global AJAX counter
615 if ( s.global && ! --jQuery.active )
616 jQuery.event.trigger( "ajaxStop" );
619 if ( s.complete ) s.complete(xml, status);
622 xml.onreadystatechange = function(){};
627 xml.onreadystatechange = onreadystatechange;
631 setTimeout(function(){
632 // Check to see if the request is still happening
634 // Cancel the request
637 if ( !requestDone ) onreadystatechange( "timeout" );
647 // return XMLHttpRequest to allow aborting the request etc.
651 // Counter for holding the number of active queries
654 // Determines if an XMLHttpRequest was successful or not
655 httpSuccess: function(r) {
657 return !r.status && location.protocol == "file:" ||
658 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
659 jQuery.browser.safari && r.status == undefined;
665 // Determines if an XMLHttpRequest returns NotModified
666 httpNotModified: function(xml, url) {
668 var xmlRes = xml.getResponseHeader("Last-Modified");
670 // Firefox always returns 200. check Last-Modified date
671 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
672 jQuery.browser.safari && xml.status == undefined;
678 /* Get the data out of an XMLHttpRequest.
679 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
680 * otherwise return plain text.
681 * (String) data - The type of data that you're expecting back,
682 * (e.g. "xml", "html", "script")
684 httpData: function(r,type) {
685 var ct = r.getResponseHeader("content-type");
686 var data = !type && ct && ct.indexOf("xml") >= 0;
687 data = type == "xml" || data ? r.responseXML : r.responseText;
689 // If the type is "script", eval it in global context
690 if ( type == "script" ) {
691 jQuery.globalEval( data );
694 // Get the JavaScript object, if JSON is used.
695 if ( type == "json" ) eval( "data = " + data );
697 // evaluate scripts within html
698 if ( type == "html" ) jQuery("<div>").html(data).evalScripts();
703 // Serialize an array of form elements or a set of
704 // key/values into a query string
708 // If an array was passed in, assume that it is an array
710 if ( a.constructor == Array || a.jquery ) {
711 // Serialize the form elements
712 for ( var i = 0; i < a.length; i++ )
713 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
715 // Otherwise, assume that it's an object of key/value pairs
717 // Serialize the key/values
719 // If the value is an array then the key names need to be repeated
720 if( a[j].constructor == Array ) {
721 for (var k = 0; k < a[j].length; k++) {
722 s.push( j + "=" + encodeURIComponent( a[j][k] ) );
725 s.push( j + "=" + encodeURIComponent( a[j] ) );
730 // Return the resulting serialization
734 // evalulates a script in global context
735 // not reliable for safari
736 globalEval: function(data) {
737 if (window.execScript)
738 window.execScript( data );
739 else if(jQuery.browser.safari)
740 // safari doesn't provide a synchronous global eval
741 window.setTimeout( data, 0 );
743 eval.call( window, data );