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' );
54 * ok( $('#foo').html() == 'foo', 'Check if script evaluation has modified DOM');
55 * ok( $('#ap').html() == 'bar', 'Check if script evaluation has modified DOM');
58 * $('#first').load('data/test.html', function() {
59 * ok( $('#first').html().match(/^html text/), 'Check content after loading html' );
60 * ok( foo == "foo", 'Check if script was evaluated after load' );
61 * setTimeout(verifyEvaluation, 600);
66 * @param String url The URL of the HTML file to load.
67 * @param Object params A set of key/value pairs that will be sent as data to the server.
68 * @param Function callback A function to be executed whenever the data is loaded (parameters: responseText, status and reponse itself).
71 load: function( url, params, callback, ifModified ) {
72 if ( url.constructor == Function )
73 return this.bind("load", url);
75 callback = callback || function(){};
77 // Default to a GET request
80 // If the second parameter was provided
83 if ( params.constructor == Function ) {
84 // We assume that it's the callback
88 // Otherwise, build a param string
90 params = jQuery.param( params );
97 // Request the remote document
102 ifModified: ifModified,
103 complete: function(res, status){
104 if ( status == "success" || !ifModified && status == "notmodified" ) {
105 // Inject the HTML into all the matched elements
106 self.html(res.responseText)
107 // Execute all the scripts inside of the newly-injected HTML
110 .each( callback, [res.responseText, status, res] );
112 callback.apply( self, [res.responseText, status, res] );
119 * Serializes a set of input elements into a string of data.
120 * This will serialize all given elements. If you need
121 * serialization similar to the form submit of a browser,
122 * you should use the form plugin. This is also true for
123 * selects with multiple attribute set, only a single option
126 * @example $("input[@type=text]").serialize();
127 * @before <input type='text' name='name' value='John'/>
128 * <input type='text' name='location' value='Boston'/>
129 * @after name=John&location=Boston
130 * @desc Serialize a selection of input elements to a string
132 * @test var data = $(':input').not('button').serialize();
133 * // ignore button, IE takes text content as value, not relevant for this test
134 * 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' );
140 serialize: function() {
141 return jQuery.param( this );
145 * Evaluate all script tags inside this jQuery. If they have a src attribute,
146 * the script is loaded, otherwise it's content is evaluated.
153 evalScripts: function() {
154 return this.find('script').each(function(){
156 // for some weird reason, it doesn't work if the callback is ommited
157 jQuery.getScript( this.src, function() {} );
159 eval.call( window, this.text || this.textContent || this.innerHTML || "" );
165 // If IE is used, create a wrapper for the XMLHttpRequest object
166 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
167 XMLHttpRequest = function(){
168 return new ActiveXObject(
169 navigator.userAgent.indexOf("MSIE 5") >= 0 ?
170 "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
174 // Attach a bunch of functions for handling common AJAX events
177 * Attach a function to be executed whenever an AJAX request begins.
179 * @example $("#loading").ajaxStart(function(){
182 * @desc Show a loading message whenever an AJAX request starts.
186 * @param Function callback The function to execute.
191 * Attach a function to be executed whenever all AJAX requests have ended.
193 * @example $("#loading").ajaxStop(function(){
196 * @desc Hide a loading message after all the AJAX requests have stopped.
200 * @param Function callback The function to execute.
205 * Attach a function to be executed whenever an AJAX request completes.
207 * @example $("#msg").ajaxComplete(function(){
208 * $(this).append("<li>Request Complete.</li>");
210 * @desc Show a message when an AJAX request completes.
214 * @param Function callback The function to execute.
219 * Attach a function to be executed whenever an AJAX request completes
222 * @example $("#msg").ajaxSuccess(function(){
223 * $(this).append("<li>Successful Request!</li>");
225 * @desc Show a message when an AJAX request completes successfully.
229 * @param Function callback The function to execute.
234 * Attach a function to be executed whenever an AJAX request fails.
236 * @example $("#msg").ajaxError(function(){
237 * $(this).append("<li>Error requesting page.</li>");
239 * @desc Show a message when an AJAX request fails.
243 * @param Function callback The function to execute.
248 * @test stop(); var counter = { complete: 0, success: 0, error: 0 };
249 * var success = function() { counter.success++ };
250 * var error = function() { counter.error++ };
251 * var complete = function() { counter.complete++ };
252 * $('#foo').ajaxStart(complete).ajaxStop(complete).ajaxComplete(complete).ajaxError(error).ajaxSuccess(success);
253 * // start with successful test
254 * $.ajax({url: "data/name.php", success: success, error: error, complete: function() {
255 * ok( counter.error == 0, 'Check succesful request' );
256 * ok( counter.success == 2, 'Check succesful request' );
257 * ok( counter.complete == 3, 'Check succesful request' );
258 * counter.error = 0; counter.success = 0; counter.complete = 0;
259 * $.ajaxTimeout(500);
260 * $.ajax({url: "data/name.php?wait=5", success: success, error: error, complete: function() {
261 * ok( counter.error == 2, 'Check failed request' );
262 * ok( counter.success == 0, 'Check failed request' );
263 * ok( counter.complete == 3, 'Check failed request' );
268 * @test stop(); var counter = { complete: 0, success: 0, error: 0 };
269 * counter.error = 0; counter.success = 0; counter.complete = 0;
270 * var success = function() { counter.success++ };
271 * var error = function() { counter.error++ };
273 * $.ajax({url: "data/name.php", global: false, success: success, error: error, complete: function() {
274 * ok( counter.error == 0, 'Check sucesful request without globals' );
275 * ok( counter.success == 1, 'Check sucesful request without globals' );
276 * ok( counter.complete == 0, 'Check sucesful request without globals' );
277 * counter.error = 0; counter.success = 0; counter.complete = 0;
278 * $.ajaxTimeout(500);
279 * $.ajax({url: "data/name.php?wait=5", global: false, success: success, error: error, complete: function() {
280 * ok( counter.error == 1, 'Check failed request without globals' );
281 * ok( counter.success == 0, 'Check failed request without globals' );
282 * ok( counter.complete == 0, 'Check failed request without globals' );
287 * @name ajaxHandlersTesting
293 var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(",");
295 for ( var i = 0; i < e.length; i++ ) new function(){
297 jQuery.fn[o] = function(f){
298 return this.bind(o, f);
306 * Load a remote page using an HTTP GET request. All of the arguments to
307 * the method (except URL) are optional.
309 * @example $.get("test.cgi")
311 * @example $.get("test.cgi", { name: "John", time: "2pm" } )
313 * @example $.get("test.cgi", function(data){
314 * alert("Data Loaded: " + data);
317 * @example $.get("test.cgi",
318 * { name: "John", time: "2pm" },
320 * alert("Data Loaded: " + data);
325 * $.get('data/dashboard.xml', function(xml) {
327 * $('tab', xml).each(function() {
328 * content.push($(this).text());
330 * ok( content[0] == 'blabla', 'Check first tab');
331 * ok( content[1] == 'blublu', 'Check second tab');
337 * @param String url The URL of the page to load.
338 * @param Hash params A set of key/value pairs that will be sent to the server.
339 * @param Function callback A function to be executed whenever the data is loaded.
342 get: function( url, data, callback, type, ifModified ) {
343 // shift arguments if data argument was ommited
344 if ( data && data.constructor == Function ) {
356 ifModified: ifModified
361 * Load a remote page using an HTTP GET request, only if it hasn't
362 * been modified since it was last retrieved. All of the arguments to
363 * the method (except URL) are optional.
365 * @example $.getIfModified("test.html")
367 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } )
369 * @example $.getIfModified("test.cgi", function(data){
370 * alert("Data Loaded: " + data);
373 * @example $.getifModified("test.cgi",
374 * { name: "John", time: "2pm" },
376 * alert("Data Loaded: " + data);
381 * $.getIfModified("data/name.php", function(msg) {
382 * ok( msg == 'ERROR', 'Check ifModified' );
386 * @name $.getIfModified
388 * @param String url The URL of the page to load.
389 * @param Hash params A set of key/value pairs that will be sent to the server.
390 * @param Function callback A function to be executed whenever the data is loaded.
393 getIfModified: function( url, data, callback, type ) {
394 jQuery.get(url, data, callback, type, 1);
398 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
399 * All of the arguments to the method (except URL) are optional.
401 * @example $.getScript("test.js")
403 * @example $.getScript("test.js", function(){
404 * alert("Script loaded and executed.");
408 * $.getScript("data/test.js", function() {
409 * ok( foobar == "bar", 'Check if script was evaluated' );
414 * $.getScript("data/test.js");
415 * ok( true, "Check with single argument, can't verify" );
419 * @param String url The URL of the page to load.
420 * @param Function callback A function to be executed whenever the data is loaded.
423 getScript: function( url, callback ) {
425 jQuery.get(url, null, callback, "script");
427 jQuery.get(url, null, null, "script");
432 * Load a remote JSON object using an HTTP GET request.
433 * All of the arguments to the method (except URL) are optional.
435 * @example $.getJSON("test.js", function(json){
436 * alert("JSON Data: " + json.users[3].name);
439 * @example $.getJSON("test.js",
440 * { name: "John", time: "2pm" },
442 * alert("JSON Data: " + json.users[3].name);
447 * $.getJSON("data/json.php", {json: "array"}, function(json) {
448 * ok( json[0].name == 'John', 'Check JSON: first, name' );
449 * ok( json[0].age == 21, 'Check JSON: first, age' );
450 * ok( json[1].name == 'Peter', 'Check JSON: second, name' );
451 * ok( json[1].age == 25, 'Check JSON: second, age' );
455 * $.getJSON("data/json.php", function(json) {
456 * ok( json.data.lang == 'en', 'Check JSON: lang' );
457 * ok( json.data.length == 25, 'Check JSON: length' );
463 * @param String url The URL of the page to load.
464 * @param Hash params A set of key/value pairs that will be sent to the server.
465 * @param Function callback A function to be executed whenever the data is loaded.
468 getJSON: function( url, data, callback ) {
470 jQuery.get(url, data, callback, "json");
472 jQuery.get(url, data, "json");
477 * Load a remote page using an HTTP POST request. All of the arguments to
478 * the method (except URL) are optional.
480 * @example $.post("test.cgi")
482 * @example $.post("test.cgi", { name: "John", time: "2pm" } )
484 * @example $.post("test.cgi", function(data){
485 * alert("Data Loaded: " + data);
488 * @example $.post("test.cgi",
489 * { name: "John", time: "2pm" },
491 * alert("Data Loaded: " + data);
496 * $.post("data/name.php", {xml: "5-2"}, function(xml){
497 * $('math', xml).each(function() {
498 * ok( $('calculation', this).text() == '5-2', 'Check for XML' );
499 * ok( $('result', this).text() == '3', 'Check for XML' );
506 * @param String url The URL of the page to load.
507 * @param Hash params A set of key/value pairs that will be sent to the server.
508 * @param Function callback A function to be executed whenever the data is loaded.
511 post: function( url, data, callback, type ) {
526 * Set the timeout of all AJAX requests to a specific amount of time.
527 * This will make all future AJAX requests timeout after a specified amount
528 * of time (the default is no timeout).
530 * @example $.ajaxTimeout( 5000 );
531 * @desc Make all AJAX requests timeout after 5 seconds.
536 * $.ajaxTimeout(1000);
537 * var pass = function() {
540 * ok( true, 'Check local and global callbacks after timeout' );
541 * clearTimeout(timeout);
542 * $('#main').unbind("ajaxError");
546 * var fail = function() {
547 * ok( false, 'Check for timeout failed' );
550 * timeout = setTimeout(fail, 1500);
551 * $('#main').ajaxError(pass);
554 * url: "data/name.php?wait=5",
559 * @test stop(); $.ajaxTimeout(50);
563 * url: "data/name.php?wait=1",
564 * error: function() {
565 * ok( false, 'Check for local timeout failed' );
568 * success: function() {
569 * ok( true, 'Check for local timeout' );
577 * @name $.ajaxTimeout
579 * @param Number time How long before an AJAX request times out.
582 ajaxTimeout: function(timeout) {
583 jQuery.timeout = timeout;
586 // Last-Modified header cache for next request
590 * Load a remote page using an HTTP request. This function is the primary
591 * means of making AJAX requests using jQuery. $.ajax() takes one property,
592 * an object of key/value pairs, that're are used to initalize the request.
594 * These are all the key/values that can be passed in to 'prop':
596 * (String) type - The type of request to make (e.g. "POST" or "GET").
598 * (String) url - The URL of the page to request.
600 * (String) data - Data to be sent to the server. If converted to a query
601 * string, if not already a string. Is appended to the url for GET-requests.
603 * (String) dataType - The type of data that you're expecting back from
604 * the server (e.g. "xml", "html", "script", or "json").
606 * (Boolean) ifModified - Allow the request to be successful only if the
607 * response has changed since the last request, default is false, ignoring
608 * the Last-Modified header
610 * (Number) timeout - Local timeout to override global timeout, eg. to give a
611 * single request a longer timeout while all others timeout after 1 seconds,
614 * (Boolean) global - Wheather to trigger global AJAX event handlers for
615 * this request, default is true. Set to true to prevent that global handlers
616 * like ajaxStart or ajaxStop are triggered.
618 * (Function) error - A function to be called if the request fails. The
619 * function gets passed two arguments: The XMLHttpRequest object and a
620 * string describing the type of error that occurred.
622 * (Function) success - A function to be called if the request succeeds. The
623 * function gets passed one argument: The data returned from the server,
624 * formatted according to the 'dataType' parameter.
626 * (Function) complete - A function to be called when the request finishes. The
627 * function gets passed two arguments: The XMLHttpRequest object and a
628 * string describing the type the success of the request.
635 * @desc Load and execute a JavaScript file.
640 * data: "name=John&location=Boston",
641 * success: function(msg){
642 * alert( "Data Saved: " + msg );
645 * @desc Save some data to the server and notify the user once its complete.
650 * url: "data/name.php?name=foo",
651 * success: function(msg){
652 * ok( msg == 'bar', 'Check for GET' );
660 * url: "data/name.php",
661 * data: "name=peter",
662 * success: function(msg){
663 * ok( msg == 'pan', 'Check for POST' );
669 * window.foobar = undefined;
670 * window.foo = undefined;
671 * var verifyEvaluation = function() {
672 * ok( foobar == "bar", 'Check if script src was evaluated for datatype html' );
677 * url: "data/test.html",
678 * success: function(data) {
679 * ok( data.match(/^html text/), 'Check content for datatype html' );
680 * ok( foo == "foo", 'Check if script was evaluated for datatype html' );
681 * setTimeout(verifyEvaluation, 600);
687 * url: "data/with_fries.xml", dataType: "xml", type: "GET", data: "", success: function(resp) {
688 * ok( $("properties", resp).length == 1, 'properties in responseXML' );
689 * ok( $("jsconf", resp).length == 1, 'jsconf in responseXML' );
690 * ok( $("thing", resp).length == 2, 'things in responseXML' );
697 * @param Hash prop A set of properties to initialize the request with.
700 ajax: function( s ) {
701 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
706 timeout: jQuery.timeout,
717 // convert data if not already a string
718 if (typeof s.data != 'string')
719 s.data = jQuery.param(s.data)
720 // append data to url for get requests
721 if( s.type.toLowerCase() == "get" )
722 // "?" + data or "&" + data (in case there are already params)
723 s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data;
726 // Watch for a new set of requests
727 if ( s.global && ! jQuery.active++ )
728 jQuery.event.trigger( "ajaxStart" );
730 var requestDone = false;
732 // Create the request object
733 var xml = new XMLHttpRequest();
736 xml.open(s.type, s.url, true);
738 // Set the correct header, if data is being sent
740 xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
742 // Set the If-Modified-Since header, if ifModified mode.
744 xml.setRequestHeader("If-Modified-Since",
745 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
747 // Set header so the called script knows that it's an XMLHttpRequest
748 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
750 // Make sure the browser sends the right content length
751 if ( xml.overrideMimeType )
752 xml.setRequestHeader("Connection", "close");
754 // Wait for a response to come back
755 var onreadystatechange = function(isTimeout){
756 // The transfer is complete and the data is available, or the request timed out
757 if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
760 var status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
761 s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
763 // Make sure that the request was successful or notmodified
764 if ( status != "error" ) {
765 // Cache Last-Modified header, if ifModified mode.
768 modRes = xml.getResponseHeader("Last-Modified");
769 } catch(e) {} // swallow exception thrown by FF if header is not available
771 if ( s.ifModified && modRes )
772 jQuery.lastModified[s.url] = modRes;
774 // If a local callback was specified, fire it
776 s.success( jQuery.httpData( xml, s.dataType ), status );
778 // Fire the global callback
780 jQuery.event.trigger( "ajaxSuccess" );
782 // Otherwise, the request was not successful
784 // If a local callback was specified, fire it
785 if ( s.error ) s.error( xml, status );
787 // Fire the global callback
789 jQuery.event.trigger( "ajaxError" );
792 // The request was completed
794 jQuery.event.trigger( "ajaxComplete" );
796 // Handle the global AJAX counter
797 if ( s.global && ! --jQuery.active )
798 jQuery.event.trigger( "ajaxStop" );
801 if ( s.complete ) s.complete(xml, status);
804 xml.onreadystatechange = function(){};
809 xml.onreadystatechange = onreadystatechange;
813 setTimeout(function(){
814 // Check to see if the request is still happening
816 // Cancel the request
819 if ( !requestDone ) onreadystatechange( "timeout" );
830 // Counter for holding the number of active queries
833 // Determines if an XMLHttpRequest was successful or not
834 httpSuccess: function(r) {
836 return !r.status && location.protocol == "file:" ||
837 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
838 jQuery.browser.safari && r.status == undefined;
844 // Determines if an XMLHttpRequest returns NotModified
845 httpNotModified: function(xml, url) {
847 var xmlRes = xml.getResponseHeader("Last-Modified");
849 // Firefox always returns 200. check Last-Modified date
850 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
851 jQuery.browser.safari && xml.status == undefined;
857 /* Get the data out of an XMLHttpRequest.
858 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
859 * otherwise return plain text.
860 * (String) data - The type of data that you're expecting back,
861 * (e.g. "xml", "html", "script")
863 httpData: function(r,type) {
864 var ct = r.getResponseHeader("content-type");
865 var data = !type && ct && ct.indexOf("xml") >= 0;
866 data = type == "xml" || data ? r.responseXML : r.responseText;
868 // If the type is "script", eval it
869 if ( type == "script" ) eval.call( window, data );
871 // Get the JavaScript object, if JSON is used.
872 if ( type == "json" ) eval( "data = " + data );
874 // evaluate scripts within html
875 if ( type == "html" ) jQuery("<div>").html(data).evalScripts();
880 // Serialize an array of form elements or a set of
881 // key/values into a query string
885 // If an array was passed in, assume that it is an array
887 if ( a.constructor == Array || a.jquery ) {
888 // Serialize the form elements
889 for ( var i = 0; i < a.length; i++ )
890 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
892 // Otherwise, assume that it's an object of key/value pairs
894 // Serialize the key/values
896 s.push( j + "=" + encodeURIComponent( a[j] ) );
899 // Return the resulting serialization