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' );
42 * @test stop(); // check if load can be called with only url
43 * $('#first').load("data/name.php");
44 * $.get("data/name.php", function() {
45 * ok( $('#first').text() == 'ERROR', 'Check if load works without callback');
51 * @param String url The URL of the HTML file to load.
52 * @param Hash params A set of key/value pairs that will be sent to the server.
53 * @param Function callback A function to be executed whenever the data is loaded.
56 load: function( url, params, callback, ifModified ) {
57 if ( url.constructor == Function )
58 return this.bind("load", url);
60 callback = callback || function(){};
62 // Default to a GET request
65 // If the second parameter was provided
68 if ( params.constructor == Function ) {
69 // We assume that it's the callback
73 // Otherwise, build a param string
75 params = jQuery.param( params );
82 // Request the remote document
83 jQuery.ajax( type, url, params,function(res, status){
85 if ( status == "success" || !ifModified && status == "notmodified" ) {
86 // Inject the HTML into all the matched elements
87 self.html(res.responseText).each( callback, [res.responseText, status] );
89 // Execute all the scripts inside of the newly-injected HTML
90 jQuery("script", self).each(function(){
92 jQuery.getScript( this.src );
94 eval.call( window, this.text || this.textContent || this.innerHTML || "" );
97 callback.apply( self, [res.responseText, status] );
105 * Serializes a set of input elements into a string of data.
106 * This will serialize all given elements. If you need
107 * serialization similar to the form submit of a browser,
108 * you should use the form plugin. This is also true for
109 * selects with multiple attribute set, only a single option
112 * @example $("input[@type=text]").serialize();
113 * @before <input type='text' name='name' value='John'/>
114 * <input type='text' name='location' value='Boston'/>
115 * @after name=John&location=Boston
116 * @desc Serialize a selection of input elements to a string
118 * @test var data = $(':input').not('button').serialize();
119 * // ignore button, IE takes text content as value, not relevant for this test
120 * 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' );
126 serialize: function() {
127 return jQuery.param( this );
132 // If IE is used, create a wrapper for the XMLHttpRequest object
133 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
134 XMLHttpRequest = function(){
135 return new ActiveXObject(
136 navigator.userAgent.indexOf("MSIE 5") >= 0 ?
137 "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
141 // Attach a bunch of functions for handling common AJAX events
144 * Attach a function to be executed whenever an AJAX request begins.
146 * @example $("#loading").ajaxStart(function(){
149 * @desc Show a loading message whenever an AJAX request starts.
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 * @example $("#msg").ajaxComplete(function(){
175 * $(this).append("<li>Request Complete.</li>");
177 * @desc Show a message when an AJAX request completes.
181 * @param Function callback The function to execute.
186 * Attach a function to be executed whenever an AJAX request completes
189 * @example $("#msg").ajaxSuccess(function(){
190 * $(this).append("<li>Successful Request!</li>");
192 * @desc Show a message when an AJAX request completes successfully.
196 * @param Function callback The function to execute.
201 * Attach a function to be executed whenever an AJAX request fails.
203 * @example $("#msg").ajaxError(function(){
204 * $(this).append("<li>Error requesting page.</li>");
206 * @desc Show a message when an AJAX request fails.
210 * @param Function callback The function to execute.
215 * @test stop(); var counter = { complete: 0, success: 0, error: 0 };
216 * var success = function() { counter.success++ };
217 * var error = function() { counter.error++ };
218 * var complete = function() { counter.complete++ };
219 * $('#foo').ajaxStart(complete).ajaxStop(complete).ajaxComplete(complete).ajaxError(error).ajaxSuccess(success);
220 * // start with successful test
221 * $.ajax({url: "data/name.php", success: success, error: error, complete: function() {
222 * ok( counter.error == 0, 'Check succesful request' );
223 * ok( counter.success == 2, 'Check succesful request' );
224 * ok( counter.complete == 3, 'Check succesful request' );
225 * counter.error = 0; counter.success = 0; counter.complete = 0;
226 * $.ajaxTimeout(500);
227 * $.ajax({url: "data/name.php?wait=5", success: success, error: error, complete: function() {
228 * ok( counter.error == 2, 'Check failed request' );
229 * ok( counter.success == 0, 'Check failed request' );
230 * ok( counter.complete == 3, 'Check failed request' );
235 * @test stop(); var counter = { complete: 0, success: 0, error: 0 };
236 * counter.error = 0; counter.success = 0; counter.complete = 0;
237 * var success = function() { counter.success++ };
238 * var error = function() { counter.error++ };
240 * $.ajax({url: "data/name.php", global: false, success: success, error: error, complete: function() {
241 * ok( counter.error == 0, 'Check sucesful request without globals' );
242 * ok( counter.success == 1, 'Check sucesful request without globals' );
243 * ok( counter.complete == 0, 'Check sucesful request without globals' );
244 * counter.error = 0; counter.success = 0; counter.complete = 0;
245 * $.ajaxTimeout(500);
246 * $.ajax({url: "data/name.php?wait=5", global: false, success: success, error: error, complete: function() {
247 * ok( counter.error == 1, 'Check failed request without globals' );
248 * ok( counter.success == 0, 'Check failed request without globals' );
249 * ok( counter.complete == 0, 'Check failed request without globals' );
254 * @name ajaxHandlersTesting
260 var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(",");
262 for ( var i = 0; i < e.length; i++ ) new function(){
264 jQuery.fn[o] = function(f){
265 return this.bind(o, f);
273 * Load a remote page using an HTTP GET request. All of the arguments to
274 * the method (except URL) are optional.
276 * @example $.get("test.cgi")
278 * @example $.get("test.cgi", { name: "John", time: "2pm" } )
280 * @example $.get("test.cgi", function(data){
281 * alert("Data Loaded: " + data);
284 * @example $.get("test.cgi",
285 * { name: "John", time: "2pm" },
287 * alert("Data Loaded: " + data);
293 * @param String url The URL of the page to load.
294 * @param Hash params A set of key/value pairs that will be sent to the server.
295 * @param Function callback A function to be executed whenever the data is loaded.
298 get: function( url, data, callback, type, ifModified ) {
299 if ( data.constructor == Function ) {
305 // append ? + data or & + data, in case there are already params
306 if ( data ) url += ((url.indexOf("?") > -1) ? "&" : "?") + jQuery.param(data);
308 // Build and start the HTTP Request
309 jQuery.ajax( "GET", url, null, function(r, status) {
310 if ( callback ) callback( jQuery.httpData(r,type), status );
315 * Load a remote page using an HTTP GET request, only if it hasn't
316 * been modified since it was last retrieved. All of the arguments to
317 * the method (except URL) are optional.
319 * @example $.getIfModified("test.html")
321 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } )
323 * @example $.getIfModified("test.cgi", function(data){
324 * alert("Data Loaded: " + data);
327 * @example $.getifModified("test.cgi",
328 * { name: "John", time: "2pm" },
330 * alert("Data Loaded: " + data);
335 * $.getIfModified("data/name.php", function(msg) {
336 * ok( msg == 'ERROR', 'Check ifModified' );
340 * @name $.getIfModified
342 * @param String url The URL of the page to load.
343 * @param Hash params A set of key/value pairs that will be sent to the server.
344 * @param Function callback A function to be executed whenever the data is loaded.
347 getIfModified: function( url, data, callback, type ) {
348 jQuery.get(url, data, callback, type, 1);
352 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
353 * All of the arguments to the method (except URL) are optional.
355 * @example $.getScript("test.js")
357 * @example $.getScript("test.js", function(){
358 * alert("Script loaded and executed.");
362 * $.getScript("data/test.js", function() {
363 * ok( foobar == "bar", 'Check if script was evaluated' );
369 * @param String url The URL of the page to load.
370 * @param Function callback A function to be executed whenever the data is loaded.
373 getScript: function( url, callback ) {
374 jQuery.get(url, callback, "script");
378 * Load a remote JSON object using an HTTP GET request.
379 * All of the arguments to the method (except URL) are optional.
381 * @example $.getJSON("test.js", function(json){
382 * alert("JSON Data: " + json.users[3].name);
385 * @example $.getJSON("test.js",
386 * { name: "John", time: "2pm" },
388 * alert("JSON Data: " + json.users[3].name);
393 * $.getJSON("data/json.php", {json: "array"}, function(json) {
394 * ok( json[0].name == 'John', 'Check JSON: first, name' );
395 * ok( json[0].age == 21, 'Check JSON: first, age' );
396 * ok( json[1].name == 'Peter', 'Check JSON: second, name' );
397 * ok( json[1].age == 25, 'Check JSON: second, age' );
401 * $.getJSON("data/json.php", function(json) {
402 * ok( json.data.lang == 'en', 'Check JSON: lang' );
403 * ok( json.data.length == 25, 'Check JSON: length' );
409 * @param String url The URL of the page to load.
410 * @param Hash params A set of key/value pairs that will be sent to the server.
411 * @param Function callback A function to be executed whenever the data is loaded.
414 getJSON: function( url, data, callback ) {
416 jQuery.get(url, data, callback, "json");
418 jQuery.get(url, data, "json");
423 * Load a remote page using an HTTP POST request. All of the arguments to
424 * the method (except URL) are optional.
426 * @example $.post("test.cgi")
428 * @example $.post("test.cgi", { name: "John", time: "2pm" } )
430 * @example $.post("test.cgi", function(data){
431 * alert("Data Loaded: " + data);
434 * @example $.post("test.cgi",
435 * { name: "John", time: "2pm" },
437 * alert("Data Loaded: " + data);
442 * $.post("data/name.php", {xml: "5-2"}, function(xml){
443 * $('math', xml).each(function() {
444 * ok( $('calculation', this).text() == '5-2', 'Check for XML' );
445 * ok( $('result', this).text() == '3', 'Check for XML' );
452 * @param String url The URL of the page to load.
453 * @param Hash params A set of key/value pairs that will be sent to the server.
454 * @param Function callback A function to be executed whenever the data is loaded.
457 post: function( url, data, callback, type ) {
458 // Build and start the HTTP Request
459 jQuery.ajax( "POST", url, jQuery.param(data), function(r, status) {
460 if ( callback ) callback( jQuery.httpData(r,type), status );
468 * Set the timeout of all AJAX requests to a specific amount of time.
469 * This will make all future AJAX requests timeout after a specified amount
470 * of time (the default is no timeout).
472 * @example $.ajaxTimeout( 5000 );
473 * @desc Make all AJAX requests timeout after 5 seconds.
478 * $.ajaxTimeout(1000);
479 * var pass = function() {
482 * ok( true, 'Check local and global callbacks after timeout' );
483 * clearTimeout(timeout);
484 * $('#main').unbind("ajaxError");
488 * var fail = function() {
489 * ok( false, 'Check for timeout failed' );
492 * timeout = setTimeout(fail, 1500);
493 * $('#main').ajaxError(pass);
496 * url: "data/name.php?wait=5",
501 * @test stop(); $.ajaxTimeout(50);
505 * url: "data/name.php?wait=1",
506 * error: function() {
507 * ok( false, 'Check for local timeout failed' );
510 * success: function() {
511 * ok( true, 'Check for local timeout' );
519 * @name $.ajaxTimeout
521 * @param Number time How long before an AJAX request times out.
524 ajaxTimeout: function(timeout) {
525 jQuery.timeout = timeout;
528 // Last-Modified header cache for next request
532 * Load a remote page using an HTTP request. This function is the primary
533 * means of making AJAX requests using jQuery. $.ajax() takes one property,
534 * an object of key/value pairs, that're are used to initalize the request.
536 * These are all the key/values that can be passed in to 'prop':
538 * (String) type - The type of request to make (e.g. "POST" or "GET").
540 * (String) url - The URL of the page to request.
542 * (String) data - A string of data to be sent to the server (POST only).
544 * (String) dataType - The type of data that you're expecting back from
545 * the server (e.g. "xml", "html", "script", or "json").
547 * (Boolean) ifModified - Allow the request to be successful only if the
548 * response has changed since the last request, default is false, ignoring
549 * the Last-Modified header
551 * (Number) timeout - Local timeout to override global timeout, eg. to give a
552 * single request a longer timeout while all others timeout after 1 seconds,
555 * (Boolean) global - Wheather to trigger global AJAX event handlers for
556 * this request, default is true. Set to true to prevent that global handlers
557 * like ajaxStart or ajaxStop are triggered.
559 * (Function) error - A function to be called if the request fails. The
560 * function gets passed two arguments: The XMLHttpRequest object and a
561 * string describing the type of error that occurred.
563 * (Function) success - A function to be called if the request succeeds. The
564 * function gets passed one argument: The data returned from the server,
565 * formatted according to the 'dataType' parameter.
567 * (Function) complete - A function to be called when the request finishes. The
568 * function gets passed two arguments: The XMLHttpRequest object and a
569 * string describing the type the success of the request.
576 * @desc Load and execute a JavaScript file.
581 * data: "name=John&location=Boston",
582 * success: function(msg){
583 * alert( "Data Saved: " + msg );
586 * @desc Save some data to the server and notify the user once its complete.
591 * url: "data/name.php?name=foo",
592 * success: function(msg){
593 * ok( msg == 'bar', 'Check for GET' );
601 * url: "data/name.php",
602 * data: "name=peter",
603 * success: function(msg){
604 * ok( msg == 'pan', 'Check for POST' );
611 * @param Hash prop A set of properties to initialize the request with.
614 ajax: function( type, url, data, ret, ifModified ) {
615 // If only a single argument was passed in,
616 // assume that it is a object of key/value pairs
619 var success = type.success;
620 var error = type.error;
621 var dataType = type.dataType;
622 var global = typeof type.global == "boolean" ? type.global : true;
623 var timeout = typeof type.timeout == "number" ? type.timeout : jQuery.timeout;
624 var ifModified = type.ifModified || false;
630 // Watch for a new set of requests
631 if ( global && ! jQuery.active++ )
632 jQuery.event.trigger( "ajaxStart" );
634 var requestDone = false;
636 // Create the request object
637 var xml = new XMLHttpRequest();
640 xml.open(type || "GET", url, true);
642 // Set the correct header, if data is being sent
644 xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
646 // Set the If-Modified-Since header, if ifModified mode.
648 xml.setRequestHeader("If-Modified-Since",
649 jQuery.lastModified[url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
651 // Set header so the called script knows that it's an XMLHttpRequest
652 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
654 // Make sure the browser sends the right content length
655 if ( xml.overrideMimeType )
656 xml.setRequestHeader("Connection", "close");
658 // Wait for a response to come back
659 var onreadystatechange = function(istimeout){
660 // The transfer is complete and the data is available, or the request timed out
661 if ( xml && (xml.readyState == 4 || istimeout == "timeout") ) {
664 var status = jQuery.httpSuccess( xml ) && istimeout != "timeout" ?
665 ifModified && jQuery.httpNotModified( xml, url ) ? "notmodified" : "success" : "error";
667 // Make sure that the request was successful or notmodified
668 if ( status != "error" ) {
669 // Cache Last-Modified header, if ifModified mode.
672 modRes = xml.getResponseHeader("Last-Modified");
673 } catch(e) {} // swallow exception thrown by FF if header is not available
675 if ( ifModified && modRes )
676 jQuery.lastModified[url] = modRes;
678 // If a local callback was specified, fire it
680 success( jQuery.httpData( xml, dataType ), status );
682 // Fire the global callback
684 jQuery.event.trigger( "ajaxSuccess" );
686 // Otherwise, the request was not successful
688 // If a local callback was specified, fire it
689 if ( error ) error( xml, status );
691 // Fire the global callback
693 jQuery.event.trigger( "ajaxError" );
696 // The request was completed
698 jQuery.event.trigger( "ajaxComplete" );
700 // Handle the global AJAX counter
701 if ( global && ! --jQuery.active )
702 jQuery.event.trigger( "ajaxStop" );
705 if ( ret ) ret(xml, status);
708 xml.onreadystatechange = function(){};
713 xml.onreadystatechange = onreadystatechange;
717 setTimeout(function(){
718 // Check to see if the request is still happening
720 // Cancel the request
723 if ( !requestDone ) onreadystatechange( "timeout" );
734 // Counter for holding the number of active queries
737 // Determines if an XMLHttpRequest was successful or not
738 httpSuccess: function(r) {
740 return !r.status && location.protocol == "file:" ||
741 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
742 jQuery.browser.safari && r.status == undefined;
748 // Determines if an XMLHttpRequest returns NotModified
749 httpNotModified: function(xml, url) {
751 var xmlRes = xml.getResponseHeader("Last-Modified");
753 // Firefox always returns 200. check Last-Modified date
754 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
755 jQuery.browser.safari && xml.status == undefined;
761 /* Get the data out of an XMLHttpRequest.
762 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
763 * otherwise return plain text.
764 * (String) data - The type of data that you're expecting back,
765 * (e.g. "xml", "html", "script")
767 httpData: function(r,type) {
768 var ct = r.getResponseHeader("content-type");
769 var data = !type && ct && ct.indexOf("xml") >= 0;
770 data = type == "xml" || data ? r.responseXML : r.responseText;
772 // If the type is "script", eval it
773 if ( type == "script" ) eval.call( window, data );
775 // Get the JavaScript object, if JSON is used.
776 if ( type == "json" ) eval( "data = " + data );
781 // Serialize an array of form elements or a set of
782 // key/values into a query string
786 // If an array was passed in, assume that it is an array
788 if ( a.constructor == Array || a.jquery ) {
789 // Serialize the form elements
790 for ( var i = 0; i < a.length; i++ )
791 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
793 // Otherwise, assume that it's an object of key/value pairs
795 // Serialize the key/values
797 s.push( j + "=" + encodeURIComponent( a[j] ) );
800 // Return the resulting serialization