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');
50 * window.foobar = undefined;
51 * window.foo = undefined;
52 * var verifyEvaluation = function() {
53 * ok( foobar == "bar", 'Check if script src was evaluated after load' );
56 * $('#first').load('data/test.html', function() {
57 * ok( $('#first').html().match(/^html text/), 'Check content after loading html' );
58 * ok( foo == "foo", 'Check if script was evaluated after load' );
59 * setTimeout(verifyEvaluation, 600);
64 * @param String url The URL of the HTML file to load.
65 * @param Hash params A set of key/value pairs that will be sent to the server.
66 * @param Function callback A function to be executed whenever the data is loaded.
69 load: function( url, params, callback, ifModified ) {
70 if ( url.constructor == Function )
71 return this.bind("load", url);
73 callback = callback || function(){};
75 // Default to a GET request
78 // If the second parameter was provided
81 if ( params.constructor == Function ) {
82 // We assume that it's the callback
86 // Otherwise, build a param string
88 params = jQuery.param( params );
95 // Request the remote document
100 ifModified: ifModified,
101 complete: function(res, status){
102 if ( status == "success" || !ifModified && status == "notmodified" ) {
103 // Inject the HTML into all the matched elements
104 self.html(res.responseText)
105 // Execute all the scripts inside of the newly-injected HTML
108 .each( callback, [res.responseText, status] );
110 callback.apply( self, [res.responseText, status] );
117 * Serializes a set of input elements into a string of data.
118 * This will serialize all given elements. If you need
119 * serialization similar to the form submit of a browser,
120 * you should use the form plugin. This is also true for
121 * selects with multiple attribute set, only a single option
124 * @example $("input[@type=text]").serialize();
125 * @before <input type='text' name='name' value='John'/>
126 * <input type='text' name='location' value='Boston'/>
127 * @after name=John&location=Boston
128 * @desc Serialize a selection of input elements to a string
130 * @test var data = $(':input').not('button').serialize();
131 * // ignore button, IE takes text content as value, not relevant for this test
132 * 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' );
138 serialize: function() {
139 return jQuery.param( this );
142 evalScripts: function() {
143 return this.find('script').each(function(){
145 // for some weird reason, it doesn't work if the callback is ommited
146 jQuery.getScript( this.src, function() {} );
148 eval.call( window, this.text || this.textContent || this.innerHTML || "" );
154 // If IE is used, create a wrapper for the XMLHttpRequest object
155 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
156 XMLHttpRequest = function(){
157 return new ActiveXObject(
158 navigator.userAgent.indexOf("MSIE 5") >= 0 ?
159 "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
163 // Attach a bunch of functions for handling common AJAX events
166 * Attach a function to be executed whenever an AJAX request begins.
168 * @example $("#loading").ajaxStart(function(){
171 * @desc Show a loading message whenever an AJAX request starts.
175 * @param Function callback The function to execute.
180 * Attach a function to be executed whenever all AJAX requests have ended.
182 * @example $("#loading").ajaxStop(function(){
185 * @desc Hide a loading message after all the AJAX requests have stopped.
189 * @param Function callback The function to execute.
194 * Attach a function to be executed whenever an AJAX request completes.
196 * @example $("#msg").ajaxComplete(function(){
197 * $(this).append("<li>Request Complete.</li>");
199 * @desc Show a message when an AJAX request completes.
203 * @param Function callback The function to execute.
208 * Attach a function to be executed whenever an AJAX request completes
211 * @example $("#msg").ajaxSuccess(function(){
212 * $(this).append("<li>Successful Request!</li>");
214 * @desc Show a message when an AJAX request completes successfully.
218 * @param Function callback The function to execute.
223 * Attach a function to be executed whenever an AJAX request fails.
225 * @example $("#msg").ajaxError(function(){
226 * $(this).append("<li>Error requesting page.</li>");
228 * @desc Show a message when an AJAX request fails.
232 * @param Function callback The function to execute.
237 * @test stop(); var counter = { complete: 0, success: 0, error: 0 };
238 * var success = function() { counter.success++ };
239 * var error = function() { counter.error++ };
240 * var complete = function() { counter.complete++ };
241 * $('#foo').ajaxStart(complete).ajaxStop(complete).ajaxComplete(complete).ajaxError(error).ajaxSuccess(success);
242 * // start with successful test
243 * $.ajax({url: "data/name.php", success: success, error: error, complete: function() {
244 * ok( counter.error == 0, 'Check succesful request' );
245 * ok( counter.success == 2, 'Check succesful request' );
246 * ok( counter.complete == 3, 'Check succesful request' );
247 * counter.error = 0; counter.success = 0; counter.complete = 0;
248 * $.ajaxTimeout(500);
249 * $.ajax({url: "data/name.php?wait=5", success: success, error: error, complete: function() {
250 * ok( counter.error == 2, 'Check failed request' );
251 * ok( counter.success == 0, 'Check failed request' );
252 * ok( counter.complete == 3, 'Check failed request' );
257 * @test stop(); var counter = { complete: 0, success: 0, error: 0 };
258 * counter.error = 0; counter.success = 0; counter.complete = 0;
259 * var success = function() { counter.success++ };
260 * var error = function() { counter.error++ };
262 * $.ajax({url: "data/name.php", global: false, success: success, error: error, complete: function() {
263 * ok( counter.error == 0, 'Check sucesful request without globals' );
264 * ok( counter.success == 1, 'Check sucesful request without globals' );
265 * ok( counter.complete == 0, 'Check sucesful request without globals' );
266 * counter.error = 0; counter.success = 0; counter.complete = 0;
267 * $.ajaxTimeout(500);
268 * $.ajax({url: "data/name.php?wait=5", global: false, success: success, error: error, complete: function() {
269 * ok( counter.error == 1, 'Check failed request without globals' );
270 * ok( counter.success == 0, 'Check failed request without globals' );
271 * ok( counter.complete == 0, 'Check failed request without globals' );
276 * @name ajaxHandlersTesting
282 var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(",");
284 for ( var i = 0; i < e.length; i++ ) new function(){
286 jQuery.fn[o] = function(f){
287 return this.bind(o, f);
295 * Load a remote page using an HTTP GET request. All of the arguments to
296 * the method (except URL) are optional.
298 * @example $.get("test.cgi")
300 * @example $.get("test.cgi", { name: "John", time: "2pm" } )
302 * @example $.get("test.cgi", function(data){
303 * alert("Data Loaded: " + data);
306 * @example $.get("test.cgi",
307 * { name: "John", time: "2pm" },
309 * alert("Data Loaded: " + data);
314 * $.get('data/dashboard.xml', function(xml) {
316 * $('tab', xml).each(function() {
317 * content.push($(this).text());
319 * ok( content[0] == 'blabla', 'Check first tab');
320 * ok( content[1] == 'blublu', 'Check second tab');
326 * @param String url The URL of the page to load.
327 * @param Hash params A set of key/value pairs that will be sent to the server.
328 * @param Function callback A function to be executed whenever the data is loaded.
331 get: function( url, data, callback, type, ifModified ) {
332 if ( data && data.constructor == Function ) {
338 // append ? + data or & + data, in case there are already params
339 if ( data ) url += ((url.indexOf("?") > -1) ? "&" : "?") + jQuery.param(data);
341 // Build and start the HTTP Request
344 ifModified: ifModified,
345 complete: function(r, status) {
346 if ( callback ) callback( jQuery.httpData(r,type), status );
352 * Load a remote page using an HTTP GET request, only if it hasn't
353 * been modified since it was last retrieved. All of the arguments to
354 * the method (except URL) are optional.
356 * @example $.getIfModified("test.html")
358 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } )
360 * @example $.getIfModified("test.cgi", function(data){
361 * alert("Data Loaded: " + data);
364 * @example $.getifModified("test.cgi",
365 * { name: "John", time: "2pm" },
367 * alert("Data Loaded: " + data);
372 * $.getIfModified("data/name.php", function(msg) {
373 * ok( msg == 'ERROR', 'Check ifModified' );
377 * @name $.getIfModified
379 * @param String url The URL of the page to load.
380 * @param Hash params A set of key/value pairs that will be sent to the server.
381 * @param Function callback A function to be executed whenever the data is loaded.
384 getIfModified: function( url, data, callback, type ) {
385 jQuery.get(url, data, callback, type, 1);
389 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
390 * All of the arguments to the method (except URL) are optional.
392 * @example $.getScript("test.js")
394 * @example $.getScript("test.js", function(){
395 * alert("Script loaded and executed.");
399 * $.getScript("data/test.js", function() {
400 * ok( foobar == "bar", 'Check if script was evaluated' );
405 * $.getScript("data/test.js");
406 * ok( true, "Check with single argument, can't verify" );
410 * @param String url The URL of the page to load.
411 * @param Function callback A function to be executed whenever the data is loaded.
414 getScript: function( url, callback ) {
416 jQuery.get(url, null, callback, "script");
418 jQuery.get(url, null, null, "script");
423 * Load a remote JSON object using an HTTP GET request.
424 * All of the arguments to the method (except URL) are optional.
426 * @example $.getJSON("test.js", function(json){
427 * alert("JSON Data: " + json.users[3].name);
430 * @example $.getJSON("test.js",
431 * { name: "John", time: "2pm" },
433 * alert("JSON Data: " + json.users[3].name);
438 * $.getJSON("data/json.php", {json: "array"}, function(json) {
439 * ok( json[0].name == 'John', 'Check JSON: first, name' );
440 * ok( json[0].age == 21, 'Check JSON: first, age' );
441 * ok( json[1].name == 'Peter', 'Check JSON: second, name' );
442 * ok( json[1].age == 25, 'Check JSON: second, age' );
446 * $.getJSON("data/json.php", function(json) {
447 * ok( json.data.lang == 'en', 'Check JSON: lang' );
448 * ok( json.data.length == 25, 'Check JSON: length' );
454 * @param String url The URL of the page to load.
455 * @param Hash params A set of key/value pairs that will be sent to the server.
456 * @param Function callback A function to be executed whenever the data is loaded.
459 getJSON: function( url, data, callback ) {
461 jQuery.get(url, data, callback, "json");
463 jQuery.get(url, data, "json");
468 * Load a remote page using an HTTP POST request. All of the arguments to
469 * the method (except URL) are optional.
471 * @example $.post("test.cgi")
473 * @example $.post("test.cgi", { name: "John", time: "2pm" } )
475 * @example $.post("test.cgi", function(data){
476 * alert("Data Loaded: " + data);
479 * @example $.post("test.cgi",
480 * { name: "John", time: "2pm" },
482 * alert("Data Loaded: " + data);
487 * $.post("data/name.php", {xml: "5-2"}, function(xml){
488 * $('math', xml).each(function() {
489 * ok( $('calculation', this).text() == '5-2', 'Check for XML' );
490 * ok( $('result', this).text() == '3', 'Check for XML' );
497 * @param String url The URL of the page to load.
498 * @param Hash params A set of key/value pairs that will be sent to the server.
499 * @param Function callback A function to be executed whenever the data is loaded.
502 post: function( url, data, callback, type ) {
503 // Build and start the HTTP Request
507 data: jQuery.param(data),
508 complete: function(r, status) {
509 if ( callback ) callback( jQuery.httpData(r,type), status );
518 * Set the timeout of all AJAX requests to a specific amount of time.
519 * This will make all future AJAX requests timeout after a specified amount
520 * of time (the default is no timeout).
522 * @example $.ajaxTimeout( 5000 );
523 * @desc Make all AJAX requests timeout after 5 seconds.
528 * $.ajaxTimeout(1000);
529 * var pass = function() {
532 * ok( true, 'Check local and global callbacks after timeout' );
533 * clearTimeout(timeout);
534 * $('#main').unbind("ajaxError");
538 * var fail = function() {
539 * ok( false, 'Check for timeout failed' );
542 * timeout = setTimeout(fail, 1500);
543 * $('#main').ajaxError(pass);
546 * url: "data/name.php?wait=5",
551 * @test stop(); $.ajaxTimeout(50);
555 * url: "data/name.php?wait=1",
556 * error: function() {
557 * ok( false, 'Check for local timeout failed' );
560 * success: function() {
561 * ok( true, 'Check for local timeout' );
569 * @name $.ajaxTimeout
571 * @param Number time How long before an AJAX request times out.
574 ajaxTimeout: function(timeout) {
575 jQuery.timeout = timeout;
578 // Last-Modified header cache for next request
582 * Load a remote page using an HTTP request. This function is the primary
583 * means of making AJAX requests using jQuery. $.ajax() takes one property,
584 * an object of key/value pairs, that're are used to initalize the request.
586 * These are all the key/values that can be passed in to 'prop':
588 * (String) type - The type of request to make (e.g. "POST" or "GET").
590 * (String) url - The URL of the page to request.
592 * (String) data - A string of data to be sent to the server (POST only).
594 * (String) dataType - The type of data that you're expecting back from
595 * the server (e.g. "xml", "html", "script", or "json").
597 * (Boolean) ifModified - Allow the request to be successful only if the
598 * response has changed since the last request, default is false, ignoring
599 * the Last-Modified header
601 * (Number) timeout - Local timeout to override global timeout, eg. to give a
602 * single request a longer timeout while all others timeout after 1 seconds,
605 * (Boolean) global - Wheather to trigger global AJAX event handlers for
606 * this request, default is true. Set to true to prevent that global handlers
607 * like ajaxStart or ajaxStop are triggered.
609 * (Function) error - A function to be called if the request fails. The
610 * function gets passed two arguments: The XMLHttpRequest object and a
611 * string describing the type of error that occurred.
613 * (Function) success - A function to be called if the request succeeds. The
614 * function gets passed one argument: The data returned from the server,
615 * formatted according to the 'dataType' parameter.
617 * (Function) complete - A function to be called when the request finishes. The
618 * function gets passed two arguments: The XMLHttpRequest object and a
619 * string describing the type the success of the request.
626 * @desc Load and execute a JavaScript file.
631 * data: "name=John&location=Boston",
632 * success: function(msg){
633 * alert( "Data Saved: " + msg );
636 * @desc Save some data to the server and notify the user once its complete.
641 * url: "data/name.php?name=foo",
642 * success: function(msg){
643 * ok( msg == 'bar', 'Check for GET' );
651 * url: "data/name.php",
652 * data: "name=peter",
653 * success: function(msg){
654 * ok( msg == 'pan', 'Check for POST' );
660 * window.foobar = undefined;
661 * window.foo = undefined;
662 * var verifyEvaluation = function() {
663 * ok( foobar == "bar", 'Check if script src was evaluated for datatype html' );
668 * url: "data/test.html",
669 * success: function(data) {
670 * ok( data.match(/^html text/), 'Check content for datatype html' );
671 * ok( foo == "foo", 'Check if script was evaluated for datatype html' );
672 * setTimeout(verifyEvaluation, 600);
678 * url: "data/with_fries.xml", dataType: "xml", type: "GET", data: "", success: function(resp) {
679 * ok( $("properties", resp).length == 1, 'properties in responseXML' );
680 * ok( $("jsconf", resp).length == 1, 'jsconf in responseXML' );
681 * ok( $("thing", resp).length == 2, 'things in responseXML' );
688 * @param Hash prop A set of properties to initialize the request with.
691 //ajax: function( type, url, data, ret, ifModified ) {
692 ajax: function( s ) {
694 var fvoid = function() {};
699 timeout: jQuery.timeout,
709 // If only a single argument was passed in,
710 // assume that it is a object of key/value pairs
713 var success = type.success;
714 var error = type.error;
715 var dataType = type.dataType;
716 var global = typeof type.global == "boolean" ? type.global : true;
717 var timeout = typeof type.timeout == "number" ? type.timeout : jQuery.timeout;
718 ifModified = type.ifModified || false;
725 // Watch for a new set of requests
726 if ( s.global && ! jQuery.active++ )
727 jQuery.event.trigger( "ajaxStart" );
729 var requestDone = false;
731 // Create the request object
732 var xml = new XMLHttpRequest();
735 xml.open(s.type, s.url, true);
737 // Set the correct header, if data is being sent
739 xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
741 // Set the If-Modified-Since header, if ifModified mode.
743 xml.setRequestHeader("If-Modified-Since",
744 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
746 // Set header so the called script knows that it's an XMLHttpRequest
747 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
749 // Make sure the browser sends the right content length
750 if ( xml.overrideMimeType )
751 xml.setRequestHeader("Connection", "close");
753 // Wait for a response to come back
754 var onreadystatechange = function(isTimeout){
755 // The transfer is complete and the data is available, or the request timed out
756 if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
759 var status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
760 s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
762 // Make sure that the request was successful or notmodified
763 if ( status != "error" ) {
764 // Cache Last-Modified header, if ifModified mode.
767 modRes = xml.getResponseHeader("Last-Modified");
768 } catch(e) {} // swallow exception thrown by FF if header is not available
770 if ( s.ifModified && modRes )
771 jQuery.lastModified[s.url] = modRes;
773 // If a local callback was specified, fire it
775 s.success( jQuery.httpData( xml, s.dataType ), status );
777 // Fire the global callback
779 jQuery.event.trigger( "ajaxSuccess" );
781 // Otherwise, the request was not successful
783 // If a local callback was specified, fire it
784 if ( s.error ) s.error( xml, status );
786 // Fire the global callback
788 jQuery.event.trigger( "ajaxError" );
791 // The request was completed
793 jQuery.event.trigger( "ajaxComplete" );
795 // Handle the global AJAX counter
796 if ( s.global && ! --jQuery.active )
797 jQuery.event.trigger( "ajaxStop" );
800 if ( s.complete ) s.complete(xml, status);
803 xml.onreadystatechange = function(){};
808 xml.onreadystatechange = onreadystatechange;
812 setTimeout(function(){
813 // Check to see if the request is still happening
815 // Cancel the request
818 if ( !requestDone ) onreadystatechange( "timeout" );
829 // Counter for holding the number of active queries
832 // Determines if an XMLHttpRequest was successful or not
833 httpSuccess: function(r) {
835 return !r.status && location.protocol == "file:" ||
836 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
837 jQuery.browser.safari && r.status == undefined;
843 // Determines if an XMLHttpRequest returns NotModified
844 httpNotModified: function(xml, url) {
846 var xmlRes = xml.getResponseHeader("Last-Modified");
848 // Firefox always returns 200. check Last-Modified date
849 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
850 jQuery.browser.safari && xml.status == undefined;
856 /* Get the data out of an XMLHttpRequest.
857 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
858 * otherwise return plain text.
859 * (String) data - The type of data that you're expecting back,
860 * (e.g. "xml", "html", "script")
862 httpData: function(r,type) {
863 var ct = r.getResponseHeader("content-type");
864 var data = !type && ct && ct.indexOf("xml") >= 0;
865 data = type == "xml" || data ? r.responseXML : r.responseText;
867 // If the type is "script", eval it
868 if ( type == "script" ) eval.call( window, data );
870 // Get the JavaScript object, if JSON is used.
871 if ( type == "json" ) eval( "data = " + data );
873 // evaluate scripts within html
874 if ( type == "html" ) jQuery("<div>").html(data).evalScripts();
879 // Serialize an array of form elements or a set of
880 // key/values into a query string
884 // If an array was passed in, assume that it is an array
886 if ( a.constructor == Array || a.jquery ) {
887 // Serialize the form elements
888 for ( var i = 0; i < a.length; i++ )
889 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
891 // Otherwise, assume that it's an object of key/value pairs
893 // Serialize the key/values
895 s.push( j + "=" + encodeURIComponent( a[j] ) );
898 // Return the resulting serialization