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');
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
96 jQuery.ajax( type, url, params,function(res, status){
98 if ( status == "success" || !ifModified && status == "notmodified" ) {
99 // Inject the HTML into all the matched elements
100 self.html(res.responseText)
101 // Execute all the scripts inside of the newly-injected HTML
104 .each( callback, [res.responseText, status] );
106 callback.apply( self, [res.responseText, status] );
114 * Serializes a set of input elements into a string of data.
115 * This will serialize all given elements. If you need
116 * serialization similar to the form submit of a browser,
117 * you should use the form plugin. This is also true for
118 * selects with multiple attribute set, only a single option
121 * @example $("input[@type=text]").serialize();
122 * @before <input type='text' name='name' value='John'/>
123 * <input type='text' name='location' value='Boston'/>
124 * @after name=John&location=Boston
125 * @desc Serialize a selection of input elements to a string
127 * @test var data = $(':input').not('button').serialize();
128 * // ignore button, IE takes text content as value, not relevant for this test
129 * 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' );
135 serialize: function() {
136 return jQuery.param( this );
139 evalScripts: function() {
140 return this.find('script').each(function(){
142 // for some weird reason, it doesn't work if the callback is ommited
143 jQuery.getScript( this.src, function() {} );
145 eval.call( window, this.text || this.textContent || this.innerHTML || "" );
151 // If IE is used, create a wrapper for the XMLHttpRequest object
152 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
153 XMLHttpRequest = function(){
154 return new ActiveXObject(
155 navigator.userAgent.indexOf("MSIE 5") >= 0 ?
156 "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
160 // Attach a bunch of functions for handling common AJAX events
163 * Attach a function to be executed whenever an AJAX request begins.
165 * @example $("#loading").ajaxStart(function(){
168 * @desc Show a loading message whenever an AJAX request starts.
172 * @param Function callback The function to execute.
177 * Attach a function to be executed whenever all AJAX requests have ended.
179 * @example $("#loading").ajaxStop(function(){
182 * @desc Hide a loading message after all the AJAX requests have stopped.
186 * @param Function callback The function to execute.
191 * Attach a function to be executed whenever an AJAX request completes.
193 * @example $("#msg").ajaxComplete(function(){
194 * $(this).append("<li>Request Complete.</li>");
196 * @desc Show a message when an AJAX request completes.
200 * @param Function callback The function to execute.
205 * Attach a function to be executed whenever an AJAX request completes
208 * @example $("#msg").ajaxSuccess(function(){
209 * $(this).append("<li>Successful Request!</li>");
211 * @desc Show a message when an AJAX request completes successfully.
215 * @param Function callback The function to execute.
220 * Attach a function to be executed whenever an AJAX request fails.
222 * @example $("#msg").ajaxError(function(){
223 * $(this).append("<li>Error requesting page.</li>");
225 * @desc Show a message when an AJAX request fails.
229 * @param Function callback The function to execute.
234 * @test stop(); var counter = { complete: 0, success: 0, error: 0 };
235 * var success = function() { counter.success++ };
236 * var error = function() { counter.error++ };
237 * var complete = function() { counter.complete++ };
238 * $('#foo').ajaxStart(complete).ajaxStop(complete).ajaxComplete(complete).ajaxError(error).ajaxSuccess(success);
239 * // start with successful test
240 * $.ajax({url: "data/name.php", success: success, error: error, complete: function() {
241 * ok( counter.error == 0, 'Check succesful request' );
242 * ok( counter.success == 2, 'Check succesful request' );
243 * ok( counter.complete == 3, 'Check succesful request' );
244 * counter.error = 0; counter.success = 0; counter.complete = 0;
245 * $.ajaxTimeout(500);
246 * $.ajax({url: "data/name.php?wait=5", success: success, error: error, complete: function() {
247 * ok( counter.error == 2, 'Check failed request' );
248 * ok( counter.success == 0, 'Check failed request' );
249 * ok( counter.complete == 3, 'Check failed request' );
254 * @test stop(); var counter = { complete: 0, success: 0, error: 0 };
255 * counter.error = 0; counter.success = 0; counter.complete = 0;
256 * var success = function() { counter.success++ };
257 * var error = function() { counter.error++ };
259 * $.ajax({url: "data/name.php", global: false, success: success, error: error, complete: function() {
260 * ok( counter.error == 0, 'Check sucesful request without globals' );
261 * ok( counter.success == 1, 'Check sucesful request without globals' );
262 * ok( counter.complete == 0, 'Check sucesful request without globals' );
263 * counter.error = 0; counter.success = 0; counter.complete = 0;
264 * $.ajaxTimeout(500);
265 * $.ajax({url: "data/name.php?wait=5", global: false, success: success, error: error, complete: function() {
266 * ok( counter.error == 1, 'Check failed request without globals' );
267 * ok( counter.success == 0, 'Check failed request without globals' );
268 * ok( counter.complete == 0, 'Check failed request without globals' );
273 * @name ajaxHandlersTesting
279 var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(",");
281 for ( var i = 0; i < e.length; i++ ) new function(){
283 jQuery.fn[o] = function(f){
284 return this.bind(o, f);
292 * Load a remote page using an HTTP GET request. All of the arguments to
293 * the method (except URL) are optional.
295 * @example $.get("test.cgi")
297 * @example $.get("test.cgi", { name: "John", time: "2pm" } )
299 * @example $.get("test.cgi", function(data){
300 * alert("Data Loaded: " + data);
303 * @example $.get("test.cgi",
304 * { name: "John", time: "2pm" },
306 * alert("Data Loaded: " + data);
311 * $.get('data/dashboard.xml', function(xml) {
313 * $('tab', xml).each(function() {
314 * content.push($(this).text());
316 * ok( content[0] == 'blabla', 'Check first tab');
317 * ok( content[1] == 'blublu', 'Check second tab');
323 * @param String url The URL of the page to load.
324 * @param Hash params A set of key/value pairs that will be sent to the server.
325 * @param Function callback A function to be executed whenever the data is loaded.
328 get: function( url, data, callback, type, ifModified ) {
329 if ( data && data.constructor == Function ) {
335 // append ? + data or & + data, in case there are already params
336 if ( data ) url += ((url.indexOf("?") > -1) ? "&" : "?") + jQuery.param(data);
338 // Build and start the HTTP Request
339 jQuery.ajax( "GET", url, null, function(r, status) {
340 if ( callback ) callback( jQuery.httpData(r,type), status );
345 * Load a remote page using an HTTP GET request, only if it hasn't
346 * been modified since it was last retrieved. All of the arguments to
347 * the method (except URL) are optional.
349 * @example $.getIfModified("test.html")
351 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } )
353 * @example $.getIfModified("test.cgi", function(data){
354 * alert("Data Loaded: " + data);
357 * @example $.getifModified("test.cgi",
358 * { name: "John", time: "2pm" },
360 * alert("Data Loaded: " + data);
365 * $.getIfModified("data/name.php", function(msg) {
366 * ok( msg == 'ERROR', 'Check ifModified' );
370 * @name $.getIfModified
372 * @param String url The URL of the page to load.
373 * @param Hash params A set of key/value pairs that will be sent to the server.
374 * @param Function callback A function to be executed whenever the data is loaded.
377 getIfModified: function( url, data, callback, type ) {
378 jQuery.get(url, data, callback, type, 1);
382 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
383 * All of the arguments to the method (except URL) are optional.
385 * @example $.getScript("test.js")
387 * @example $.getScript("test.js", function(){
388 * alert("Script loaded and executed.");
392 * $.getScript("data/test.js", function() {
393 * ok( foobar == "bar", 'Check if script was evaluated' );
398 * $.getScript("data/test.js");
399 * ok( true, "Check with single argument, can't verify" );
403 * @param String url The URL of the page to load.
404 * @param Function callback A function to be executed whenever the data is loaded.
407 getScript: function( url, callback ) {
409 jQuery.get(url, null, callback, "script");
411 jQuery.get(url, null, null, "script");
416 * Load a remote JSON object using an HTTP GET request.
417 * All of the arguments to the method (except URL) are optional.
419 * @example $.getJSON("test.js", function(json){
420 * alert("JSON Data: " + json.users[3].name);
423 * @example $.getJSON("test.js",
424 * { name: "John", time: "2pm" },
426 * alert("JSON Data: " + json.users[3].name);
431 * $.getJSON("data/json.php", {json: "array"}, function(json) {
432 * ok( json[0].name == 'John', 'Check JSON: first, name' );
433 * ok( json[0].age == 21, 'Check JSON: first, age' );
434 * ok( json[1].name == 'Peter', 'Check JSON: second, name' );
435 * ok( json[1].age == 25, 'Check JSON: second, age' );
439 * $.getJSON("data/json.php", function(json) {
440 * ok( json.data.lang == 'en', 'Check JSON: lang' );
441 * ok( json.data.length == 25, 'Check JSON: length' );
447 * @param String url The URL of the page to load.
448 * @param Hash params A set of key/value pairs that will be sent to the server.
449 * @param Function callback A function to be executed whenever the data is loaded.
452 getJSON: function( url, data, callback ) {
454 jQuery.get(url, data, callback, "json");
456 jQuery.get(url, data, "json");
461 * Load a remote page using an HTTP POST request. All of the arguments to
462 * the method (except URL) are optional.
464 * @example $.post("test.cgi")
466 * @example $.post("test.cgi", { name: "John", time: "2pm" } )
468 * @example $.post("test.cgi", function(data){
469 * alert("Data Loaded: " + data);
472 * @example $.post("test.cgi",
473 * { name: "John", time: "2pm" },
475 * alert("Data Loaded: " + data);
480 * $.post("data/name.php", {xml: "5-2"}, function(xml){
481 * $('math', xml).each(function() {
482 * ok( $('calculation', this).text() == '5-2', 'Check for XML' );
483 * ok( $('result', this).text() == '3', 'Check for XML' );
490 * @param String url The URL of the page to load.
491 * @param Hash params A set of key/value pairs that will be sent to the server.
492 * @param Function callback A function to be executed whenever the data is loaded.
495 post: function( url, data, callback, type ) {
496 // Build and start the HTTP Request
497 jQuery.ajax( "POST", url, jQuery.param(data), function(r, status) {
498 if ( callback ) callback( jQuery.httpData(r,type), status );
506 * Set the timeout of all AJAX requests to a specific amount of time.
507 * This will make all future AJAX requests timeout after a specified amount
508 * of time (the default is no timeout).
510 * @example $.ajaxTimeout( 5000 );
511 * @desc Make all AJAX requests timeout after 5 seconds.
516 * $.ajaxTimeout(1000);
517 * var pass = function() {
520 * ok( true, 'Check local and global callbacks after timeout' );
521 * clearTimeout(timeout);
522 * $('#main').unbind("ajaxError");
526 * var fail = function() {
527 * ok( false, 'Check for timeout failed' );
530 * timeout = setTimeout(fail, 1500);
531 * $('#main').ajaxError(pass);
534 * url: "data/name.php?wait=5",
539 * @test stop(); $.ajaxTimeout(50);
543 * url: "data/name.php?wait=1",
544 * error: function() {
545 * ok( false, 'Check for local timeout failed' );
548 * success: function() {
549 * ok( true, 'Check for local timeout' );
557 * @name $.ajaxTimeout
559 * @param Number time How long before an AJAX request times out.
562 ajaxTimeout: function(timeout) {
563 jQuery.timeout = timeout;
566 // Last-Modified header cache for next request
570 * Load a remote page using an HTTP request. This function is the primary
571 * means of making AJAX requests using jQuery. $.ajax() takes one property,
572 * an object of key/value pairs, that're are used to initalize the request.
574 * These are all the key/values that can be passed in to 'prop':
576 * (String) type - The type of request to make (e.g. "POST" or "GET").
578 * (String) url - The URL of the page to request.
580 * (String) data - A string of data to be sent to the server (POST only).
582 * (String) dataType - The type of data that you're expecting back from
583 * the server (e.g. "xml", "html", "script", or "json").
585 * (Boolean) ifModified - Allow the request to be successful only if the
586 * response has changed since the last request, default is false, ignoring
587 * the Last-Modified header
589 * (Number) timeout - Local timeout to override global timeout, eg. to give a
590 * single request a longer timeout while all others timeout after 1 seconds,
593 * (Boolean) global - Wheather to trigger global AJAX event handlers for
594 * this request, default is true. Set to true to prevent that global handlers
595 * like ajaxStart or ajaxStop are triggered.
597 * (Function) error - A function to be called if the request fails. The
598 * function gets passed two arguments: The XMLHttpRequest object and a
599 * string describing the type of error that occurred.
601 * (Function) success - A function to be called if the request succeeds. The
602 * function gets passed one argument: The data returned from the server,
603 * formatted according to the 'dataType' parameter.
605 * (Function) complete - A function to be called when the request finishes. The
606 * function gets passed two arguments: The XMLHttpRequest object and a
607 * string describing the type the success of the request.
614 * @desc Load and execute a JavaScript file.
619 * data: "name=John&location=Boston",
620 * success: function(msg){
621 * alert( "Data Saved: " + msg );
624 * @desc Save some data to the server and notify the user once its complete.
629 * url: "data/name.php?name=foo",
630 * success: function(msg){
631 * ok( msg == 'bar', 'Check for GET' );
639 * url: "data/name.php",
640 * data: "name=peter",
641 * success: function(msg){
642 * ok( msg == 'pan', 'Check for POST' );
648 * foobar = undefined;
650 * var verifyEvaluation = function() {
651 * ok( foobar == "bar", 'Check if script src was evaluated for datatype html' );
656 * url: "data/test.html",
657 * success: function(data) {
658 * ok( data.match(/^html text/), 'Check content for datatype html' );
659 * ok( foo == "foo", 'Check if script was evaluated for datatype html' );
660 * setTimeout(verifyEvaluation, 600);
666 * url: "data/with_fries.xml", dataType: "xml", type: "GET", data: "", success: function(resp) {
667 * ok( $("properties", resp).length == 1, 'properties in responseXML' );
668 * ok( $("jsconf", resp).length == 1, 'jsconf in responseXML' );
669 * ok( $("thing", resp).length == 2, 'things in responseXML' );
676 * @param Hash prop A set of properties to initialize the request with.
679 ajax: function( type, url, data, ret, ifModified ) {
680 // If only a single argument was passed in,
681 // assume that it is a object of key/value pairs
683 var timeout = jQuery.timeout;
686 var success = type.success;
687 var error = type.error;
688 var dataType = type.dataType;
689 var global = typeof type.global == "boolean" ? type.global : true;
690 var timeout = typeof type.timeout == "number" ? type.timeout : jQuery.timeout;
691 ifModified = type.ifModified || false;
697 // Watch for a new set of requests
698 if ( global && ! jQuery.active++ )
699 jQuery.event.trigger( "ajaxStart" );
701 var requestDone = false;
703 // Create the request object
704 var xml = new XMLHttpRequest();
707 xml.open(type || "GET", url, true);
709 // Set the correct header, if data is being sent
711 xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
713 // Set the If-Modified-Since header, if ifModified mode.
715 xml.setRequestHeader("If-Modified-Since",
716 jQuery.lastModified[url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
718 // Set header so the called script knows that it's an XMLHttpRequest
719 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
721 // Make sure the browser sends the right content length
722 if ( xml.overrideMimeType )
723 xml.setRequestHeader("Connection", "close");
725 // Wait for a response to come back
726 var onreadystatechange = function(istimeout){
727 // The transfer is complete and the data is available, or the request timed out
728 if ( xml && (xml.readyState == 4 || istimeout == "timeout") ) {
731 var status = jQuery.httpSuccess( xml ) && istimeout != "timeout" ?
732 ifModified && jQuery.httpNotModified( xml, url ) ? "notmodified" : "success" : "error";
734 // Make sure that the request was successful or notmodified
735 if ( status != "error" ) {
736 // Cache Last-Modified header, if ifModified mode.
739 modRes = xml.getResponseHeader("Last-Modified");
740 } catch(e) {} // swallow exception thrown by FF if header is not available
742 if ( ifModified && modRes )
743 jQuery.lastModified[url] = modRes;
745 // If a local callback was specified, fire it
747 success( jQuery.httpData( xml, dataType ), status );
749 // Fire the global callback
751 jQuery.event.trigger( "ajaxSuccess" );
753 // Otherwise, the request was not successful
755 // If a local callback was specified, fire it
756 if ( error ) error( xml, status );
758 // Fire the global callback
760 jQuery.event.trigger( "ajaxError" );
763 // The request was completed
765 jQuery.event.trigger( "ajaxComplete" );
767 // Handle the global AJAX counter
768 if ( global && ! --jQuery.active )
769 jQuery.event.trigger( "ajaxStop" );
772 if ( ret ) ret(xml, status);
775 xml.onreadystatechange = function(){};
780 xml.onreadystatechange = onreadystatechange;
784 setTimeout(function(){
785 // Check to see if the request is still happening
787 // Cancel the request
790 if ( !requestDone ) onreadystatechange( "timeout" );
801 // Counter for holding the number of active queries
804 // Determines if an XMLHttpRequest was successful or not
805 httpSuccess: function(r) {
807 return !r.status && location.protocol == "file:" ||
808 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
809 jQuery.browser.safari && r.status == undefined;
815 // Determines if an XMLHttpRequest returns NotModified
816 httpNotModified: function(xml, url) {
818 var xmlRes = xml.getResponseHeader("Last-Modified");
820 // Firefox always returns 200. check Last-Modified date
821 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
822 jQuery.browser.safari && xml.status == undefined;
828 /* Get the data out of an XMLHttpRequest.
829 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
830 * otherwise return plain text.
831 * (String) data - The type of data that you're expecting back,
832 * (e.g. "xml", "html", "script")
834 httpData: function(r,type) {
835 var ct = r.getResponseHeader("content-type");
836 var data = !type && ct && ct.indexOf("xml") >= 0;
837 data = type == "xml" || data ? r.responseXML : r.responseText;
839 // If the type is "script", eval it
840 if ( type == "script" ) eval.call( window, data );
842 // Get the JavaScript object, if JSON is used.
843 if ( type == "json" ) eval( "data = " + data );
845 // evaluate scripts within html
846 if ( type == "html" ) $("<div>").html(data).evalScripts();
851 // Serialize an array of form elements or a set of
852 // key/values into a query string
856 // If an array was passed in, assume that it is an array
858 if ( a.constructor == Array || a.jquery ) {
859 // Serialize the form elements
860 for ( var i = 0; i < a.length; i++ )
861 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
863 // Otherwise, assume that it's an object of key/value pairs
865 // Serialize the key/values
867 s.push( j + "=" + encodeURIComponent( a[j] ) );
870 // Return the resulting serialization