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.
37 * $('#first').load("data/name.php", function() {
38 * ok( $('#first').text() == 'ERROR', 'Check if content was injected into the DOM' );
44 * @param String url The URL of the HTML file to load.
45 * @param Hash params A set of key/value pairs that will be sent to the server.
46 * @param Function callback A function to be executed whenever the data is loaded.
49 load: function( url, params, callback, ifModified ) {
50 if ( url.constructor == Function )
51 return this.bind("load", url);
53 callback = callback || function(){};
55 // Default to a GET request
58 // If the second parameter was provided
61 if ( params.constructor == Function ) {
62 // We assume that it's the callback
66 // Otherwise, build a param string
68 params = jQuery.param( params );
75 // Request the remote document
76 jQuery.ajax( type, url, params,function(res, status){
78 if ( status == "success" || !ifModified && status == "notmodified" ) {
79 // Inject the HTML into all the matched elements
80 self.html(res.responseText).each( callback, [res.responseText, status] );
82 // Execute all the scripts inside of the newly-injected HTML
83 $("script", self).each(function(){
85 $.getScript( this.src );
87 eval.call( window, this.text || this.textContent || this.innerHTML || "" );
90 callback.apply( self, [res.responseText, status] );
98 * Serializes a set of input elements into a string of data.
99 * This will serialize all given elements. If you need
100 * serialization similar to the form submit of a browser,
101 * you should use the form plugin. This is also true for
102 * selects with multiple attribute set, only a single option
105 * @example $("input[@type=text]").serialize();
106 * @before <input type='text' name='name' value='John'/>
107 * <input type='text' name='location' value='Boston'/>
108 * @after name=John&location=Boston
109 * @desc Serialize a selection of input elements to a string
111 * @test var data = $(':input').not('button').serialize();
112 * // ignore button, IE takes text content as value, not relevant for this test
113 * ok( data == 'action=Test&text2=Test&radio1=on&radio2=on&check=on&=on&hidden=&foo[bar]=&name=name&=foobar&select1=&select2=3&select3=1', 'Check form serialization as query string' );
119 serialize: function() {
120 return $.param( this );
125 // If IE is used, create a wrapper for the XMLHttpRequest object
126 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
127 XMLHttpRequest = function(){
128 return new ActiveXObject(
129 navigator.userAgent.indexOf("MSIE 5") >= 0 ?
130 "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
134 // Attach a bunch of functions for handling common AJAX events
137 * Attach a function to be executed whenever an AJAX request begins.
139 * @example $("#loading").ajaxStart(function(){
142 * @desc Show a loading message whenever an AJAX request starts.
146 * @param Function callback The function to execute.
151 * Attach a function to be executed whenever all AJAX requests have ended.
153 * @example $("#loading").ajaxStop(function(){
156 * @desc Hide a loading message after all the AJAX requests have stopped.
160 * @param Function callback The function to execute.
165 * Attach a function to be executed whenever an AJAX request completes.
167 * @example $("#msg").ajaxComplete(function(){
168 * $(this).append("<li>Request Complete.</li>");
170 * @desc Show a message when an AJAX request completes.
174 * @param Function callback The function to execute.
179 * Attach a function to be executed whenever an AJAX request completes
182 * @example $("#msg").ajaxSuccess(function(){
183 * $(this).append("<li>Successful Request!</li>");
185 * @desc Show a message when an AJAX request completes successfully.
189 * @param Function callback The function to execute.
194 * Attach a function to be executed whenever an AJAX request fails.
196 * @example $("#msg").ajaxError(function(){
197 * $(this).append("<li>Error requesting page.</li>");
199 * @desc Show a message when an AJAX request fails.
203 * @param Function callback The function to execute.
208 * @test stop(); var counter = { complete: 0, success: 0, error: 0 };
209 * var success = function() { counter.success++ };
210 * var error = function() { counter.error++ };
211 * var complete = function() { counter.complete++ };
212 * $('#foo').ajaxStart(complete).ajaxStop(complete).ajaxComplete(complete).ajaxError(error).ajaxSuccess(success);
213 * // start with successful test
214 * $.ajax({url: "data/name.php", success: success, error: error, complete: function() {
215 * ok( counter.error == 0, 'Check succesful request' );
216 * ok( counter.success == 2, 'Check succesful request' );
217 * ok( counter.complete == 3, 'Check succesful request' );
218 * counter.error = 0; counter.success = 0; counter.complete = 0;
219 * $.ajaxTimeout(500);
220 * $.ajax({url: "data/name.php?wait=5", success: success, error: error, complete: function() {
221 * ok( counter.error == 2, 'Check failed request' );
222 * ok( counter.success == 0, 'Check failed request' );
223 * ok( counter.complete == 3, 'Check failed request' );
228 * @test stop(); var counter = { complete: 0, success: 0, error: 0 };
229 * counter.error = 0; counter.success = 0; counter.complete = 0;
230 * var success = function() { counter.success++ };
231 * var error = function() { counter.error++ };
233 * $.ajax({url: "data/name.php", global: false, success: success, error: error, complete: function() {
234 * ok( counter.error == 0, 'Check sucesful request without globals' );
235 * ok( counter.success == 1, 'Check sucesful request without globals' );
236 * ok( counter.complete == 0, 'Check sucesful request without globals' );
237 * counter.error = 0; counter.success = 0; counter.complete = 0;
238 * $.ajaxTimeout(500);
239 * $.ajax({url: "data/name.php?wait=5", global: false, success: success, error: error, complete: function() {
240 * ok( counter.error == 1, 'Check failed request without globals' );
241 * ok( counter.success == 0, 'Check failed request without globals' );
242 * ok( counter.complete == 0, 'Check failed request without globals' );
247 * @name ajaxHandlersTesting
253 var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(",");
255 for ( var i = 0; i < e.length; i++ ) new function(){
257 jQuery.fn[o] = function(f){
258 return this.bind(o, f);
266 * Load a remote page using an HTTP GET request. All of the arguments to
267 * the method (except URL) are optional.
269 * @example $.get("test.cgi")
271 * @example $.get("test.cgi", { name: "John", time: "2pm" } )
273 * @example $.get("test.cgi", function(data){
274 * alert("Data Loaded: " + data);
277 * @example $.get("test.cgi",
278 * { name: "John", time: "2pm" },
280 * alert("Data Loaded: " + data);
285 * $.get("data/dashboard.xml", function(xml) {
287 * $('tab', xml).each(function(k) {
288 * // workaround for IE needed here, $(this).text() throws an error
289 * // content[k] = $.trim(this.firstChild.data) || $(this).text();
290 * content[k] = $(this).text();
292 * ok( content[0] && content[0].match(/blabla/), 'Check first tab' );
293 * ok( content[1] && content[1].match(/blublu/), 'Check second tab' );
299 * @param String url The URL of the page to load.
300 * @param Hash params A set of key/value pairs that will be sent to the server.
301 * @param Function callback A function to be executed whenever the data is loaded.
304 get: function( url, data, callback, type, ifModified ) {
305 if ( data.constructor == Function ) {
311 // append ? + data or & + data, in case there are already params
312 if ( data ) url += ((url.indexOf("?") > -1) ? "&" : "?") + jQuery.param(data);
314 // Build and start the HTTP Request
315 jQuery.ajax( "GET", url, null, function(r, status) {
316 if ( callback ) callback( jQuery.httpData(r,type), status );
321 * Load a remote page using an HTTP GET request, only if it hasn't
322 * been modified since it was last retrieved. All of the arguments to
323 * the method (except URL) are optional.
325 * @example $.getIfModified("test.html")
327 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } )
329 * @example $.getIfModified("test.cgi", function(data){
330 * alert("Data Loaded: " + data);
333 * @example $.getifModified("test.cgi",
334 * { name: "John", time: "2pm" },
336 * alert("Data Loaded: " + data);
341 * $.getIfModified("data/name.php", function(msg) {
342 * ok( msg == 'ERROR', 'Check ifModified' );
346 * @name $.getIfModified
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 getIfModified: function( url, data, callback, type ) {
354 jQuery.get(url, data, callback, type, 1);
358 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
359 * All of the arguments to the method (except URL) are optional.
361 * @example $.getScript("test.js")
363 * @example $.getScript("test.js", function(){
364 * alert("Script loaded and executed.");
368 * $.getScript("data/test.js", function() {
369 * ok( foobar == "bar", 'Check if script was evaluated' );
375 * @param String url The URL of the page to load.
376 * @param Function callback A function to be executed whenever the data is loaded.
379 getScript: function( url, callback ) {
380 jQuery.get(url, callback, "script");
384 * Load a remote JSON object using an HTTP GET request.
385 * All of the arguments to the method (except URL) are optional.
387 * @example $.getJSON("test.js", function(json){
388 * alert("JSON Data: " + json.users[3].name);
391 * @example $.getJSON("test.js",
392 * { name: "John", time: "2pm" },
394 * alert("JSON Data: " + json.users[3].name);
399 * $.getJSON("data/json.php", {json: "array"}, function(json) {
400 * ok( json[0].name == 'John', 'Check JSON: first, name' );
401 * ok( json[0].age == 21, 'Check JSON: first, age' );
402 * ok( json[1].name == 'Peter', 'Check JSON: second, name' );
403 * ok( json[1].age == 25, 'Check JSON: second, age' );
407 * $.getJSON("data/json.php", function(json) {
408 * ok( json.data.lang == 'en', 'Check JSON: lang' );
409 * ok( json.data.length == 25, 'Check JSON: length' );
415 * @param String url The URL of the page to load.
416 * @param Hash params A set of key/value pairs that will be sent to the server.
417 * @param Function callback A function to be executed whenever the data is loaded.
420 getJSON: function( url, data, callback ) {
422 jQuery.get(url, data, callback, "json");
424 jQuery.get(url, data, "json");
429 * Load a remote page using an HTTP POST request. All of the arguments to
430 * the method (except URL) are optional.
432 * @example $.post("test.cgi")
434 * @example $.post("test.cgi", { name: "John", time: "2pm" } )
436 * @example $.post("test.cgi", function(data){
437 * alert("Data Loaded: " + data);
440 * @example $.post("test.cgi",
441 * { name: "John", time: "2pm" },
443 * alert("Data Loaded: " + data);
448 * $.post("data/name.php", {xml: "5-2"}, function(xml){
449 * $('math', xml).each(function() {
450 * ok( $('calculation', this).text() == '5-2', 'Check for XML' );
451 * ok( $('result', this).text() == '3', 'Check for XML' );
458 * @param String url The URL of the page to load.
459 * @param Hash params A set of key/value pairs that will be sent to the server.
460 * @param Function callback A function to be executed whenever the data is loaded.
463 post: function( url, data, callback, type ) {
464 // Build and start the HTTP Request
465 jQuery.ajax( "POST", url, jQuery.param(data), function(r, status) {
466 if ( callback ) callback( jQuery.httpData(r,type), status );
474 * Set the timeout of all AJAX requests to a specific amount of time.
475 * This will make all future AJAX requests timeout after a specified amount
476 * of time (the default is no timeout).
478 * @example $.ajaxTimeout( 5000 );
479 * @desc Make all AJAX requests timeout after 5 seconds.
484 * $.ajaxTimeout(1000);
485 * var pass = function() {
488 * ok( true, 'Check local and global callbacks after timeout' );
489 * clearTimeout(timeout);
490 * $('#main').unbind("ajaxError");
494 * var fail = function() {
495 * ok( false, 'Check for timeout failed' );
498 * timeout = setTimeout(fail, 1500);
499 * $('#main').ajaxError(pass);
502 * url: "data/name.php?wait=5",
507 * @test stop(); $.ajaxTimeout(50);
511 * url: "data/name.php?wait=1",
512 * error: function() {
513 * ok( false, 'Check for local timeout failed' );
516 * success: function() {
517 * ok( true, 'Check for local timeout' );
525 * @name $.ajaxTimeout
527 * @param Number time How long before an AJAX request times out.
530 ajaxTimeout: function(timeout) {
531 jQuery.timeout = timeout;
534 // Last-Modified header cache for next request
538 * Load a remote page using an HTTP request. This function is the primary
539 * means of making AJAX requests using jQuery. $.ajax() takes one property,
540 * an object of key/value pairs, that're are used to initalize the request.
542 * These are all the key/values that can be passed in to 'prop':
544 * (String) type - The type of request to make (e.g. "POST" or "GET").
546 * (String) url - The URL of the page to request.
548 * (String) data - A string of data to be sent to the server (POST only).
550 * (String) dataType - The type of data that you're expecting back from
551 * the server (e.g. "xml", "html", "script", or "json").
553 * (Boolean) ifModified - Allow the request to be successful only if the
554 * response has changed since the last request, default is false, ignoring
555 * the Last-Modified header
557 * (Number) timeout - Local timeout to override global timeout, eg. to give a
558 * single request a longer timeout while all others timeout after 1 seconds,
561 * (Boolean) global - Wheather to trigger global AJAX event handlers for
562 * this request, default is true. Set to true to prevent that global handlers
563 * like ajaxStart or ajaxStop are triggered.
565 * (Function) error - A function to be called if the request fails. The
566 * function gets passed two arguments: The XMLHttpRequest object and a
567 * string describing the type of error that occurred.
569 * (Function) success - A function to be called if the request succeeds. The
570 * function gets passed one argument: The data returned from the server,
571 * formatted according to the 'dataType' parameter.
573 * (Function) complete - A function to be called when the request finishes. The
574 * function gets passed two arguments: The XMLHttpRequest object and a
575 * string describing the type the success of the request.
582 * @desc Load and execute a JavaScript file.
587 * data: "name=John&location=Boston",
588 * success: function(msg){
589 * alert( "Data Saved: " + msg );
592 * @desc Save some data to the server and notify the user once its complete.
597 * url: "data/name.php?name=foo",
598 * success: function(msg){
599 * ok( msg == 'bar', 'Check for GET' );
607 * url: "data/name.php",
608 * data: "name=peter",
609 * success: function(msg){
610 * ok( msg == 'pan', 'Check for POST' );
617 * @param Hash prop A set of properties to initialize the request with.
620 ajax: function( type, url, data, ret, ifModified ) {
621 // If only a single argument was passed in,
622 // assume that it is a object of key/value pairs
625 var success = type.success;
626 var error = type.error;
627 var dataType = type.dataType;
628 var global = typeof type.global == "boolean" ? type.global : true;
629 var timeout = typeof type.timeout == "number" ? type.timeout : jQuery.timeout;
630 var ifModified = type.ifModified || false;
636 // Watch for a new set of requests
637 if ( global && ! jQuery.active++ )
638 jQuery.event.trigger( "ajaxStart" );
640 var requestDone = false;
642 // Create the request object
643 var xml = new XMLHttpRequest();
646 xml.open(type || "GET", url, true);
648 // Set the correct header, if data is being sent
650 xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
652 // Set the If-Modified-Since header, if ifModified mode.
654 xml.setRequestHeader("If-Modified-Since",
655 jQuery.lastModified[url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
657 // Set header so the called script knows that it's an XMLHttpRequest
658 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
660 // Make sure the browser sends the right content length
661 if ( xml.overrideMimeType )
662 xml.setRequestHeader("Connection", "close");
664 // Wait for a response to come back
665 var onreadystatechange = function(istimeout){
666 // The transfer is complete and the data is available, or the request timed out
667 if ( xml && (xml.readyState == 4 || istimeout == "timeout") ) {
670 var status = jQuery.httpSuccess( xml ) && istimeout != "timeout" ?
671 ifModified && jQuery.httpNotModified( xml, url ) ? "notmodified" : "success" : "error";
673 // Make sure that the request was successful or notmodified
674 if ( status != "error" ) {
675 // Cache Last-Modified header, if ifModified mode.
678 modRes = xml.getResponseHeader("Last-Modified");
679 } catch(e) {} // swallow exception thrown by FF if header is not available
681 if ( ifModified && modRes )
682 jQuery.lastModified[url] = modRes;
684 // If a local callback was specified, fire it
686 success( jQuery.httpData( xml, dataType ), status );
688 // Fire the global callback
690 jQuery.event.trigger( "ajaxSuccess" );
692 // Otherwise, the request was not successful
694 // If a local callback was specified, fire it
695 if ( error ) error( xml, status );
697 // Fire the global callback
699 jQuery.event.trigger( "ajaxError" );
702 // The request was completed
704 jQuery.event.trigger( "ajaxComplete" );
706 // Handle the global AJAX counter
707 if ( global && ! --jQuery.active )
708 jQuery.event.trigger( "ajaxStop" );
711 if ( ret ) ret(xml, status);
714 xml.onreadystatechange = function(){};
719 xml.onreadystatechange = onreadystatechange;
723 setTimeout(function(){
724 // Check to see if the request is still happening
726 // Cancel the request
729 if ( !requestDone ) onreadystatechange( "timeout" );
740 // Counter for holding the number of active queries
743 // Determines if an XMLHttpRequest was successful or not
744 httpSuccess: function(r) {
746 return !r.status && location.protocol == "file:" ||
747 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
748 jQuery.browser.safari && r.status == undefined;
754 // Determines if an XMLHttpRequest returns NotModified
755 httpNotModified: function(xml, url) {
757 var xmlRes = xml.getResponseHeader("Last-Modified");
759 // Firefox always returns 200. check Last-Modified date
760 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
761 jQuery.browser.safari && xml.status == undefined;
767 /* Get the data out of an XMLHttpRequest.
768 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
769 * otherwise return plain text.
770 * (String) data - The type of data that you're expecting back,
771 * (e.g. "xml", "html", "script")
773 httpData: function(r,type) {
774 var ct = r.getResponseHeader("content-type");
775 var data = !type && ct && ct.indexOf("xml") >= 0;
776 data = type == "xml" || data ? r.responseXML : r.responseText;
778 // If the type is "script", eval it
779 if ( type == "script" ) eval.call( window, data );
781 // Get the JavaScript object, if JSON is used.
782 if ( type == "json" ) eval( "data = " + data );
787 // Serialize an array of form elements or a set of
788 // key/values into a query string
792 // If an array was passed in, assume that it is an array
794 if ( a.constructor == Array || a.jquery ) {
795 // Serialize the form elements
796 for ( var i = 0; i < a.length; i++ )
797 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
799 // Otherwise, assume that it's an object of key/value pairs
801 // Serialize the key/values
803 s.push( j + "=" + encodeURIComponent( a[j] ) );
806 // Return the resulting serialization