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 to the server.
68 * @param Function callback A function to be executed whenever the data is loaded.
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] );
112 callback.apply( self, [res.responseText, status] );
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 );
144 evalScripts: function() {
145 return this.find('script').each(function(){
147 // for some weird reason, it doesn't work if the callback is ommited
148 jQuery.getScript( this.src, function() {} );
150 eval.call( window, this.text || this.textContent || this.innerHTML || "" );
156 // If IE is used, create a wrapper for the XMLHttpRequest object
157 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
158 XMLHttpRequest = function(){
159 return new ActiveXObject(
160 navigator.userAgent.indexOf("MSIE 5") >= 0 ?
161 "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
165 // Attach a bunch of functions for handling common AJAX events
168 * Attach a function to be executed whenever an AJAX request begins.
170 * @example $("#loading").ajaxStart(function(){
173 * @desc Show a loading message whenever an AJAX request starts.
177 * @param Function callback The function to execute.
182 * Attach a function to be executed whenever all AJAX requests have ended.
184 * @example $("#loading").ajaxStop(function(){
187 * @desc Hide a loading message after all the AJAX requests have stopped.
191 * @param Function callback The function to execute.
196 * Attach a function to be executed whenever an AJAX request completes.
198 * @example $("#msg").ajaxComplete(function(){
199 * $(this).append("<li>Request Complete.</li>");
201 * @desc Show a message when an AJAX request completes.
205 * @param Function callback The function to execute.
210 * Attach a function to be executed whenever an AJAX request completes
213 * @example $("#msg").ajaxSuccess(function(){
214 * $(this).append("<li>Successful Request!</li>");
216 * @desc Show a message when an AJAX request completes successfully.
220 * @param Function callback The function to execute.
225 * Attach a function to be executed whenever an AJAX request fails.
227 * @example $("#msg").ajaxError(function(){
228 * $(this).append("<li>Error requesting page.</li>");
230 * @desc Show a message when an AJAX request fails.
234 * @param Function callback The function to execute.
239 * @test stop(); var counter = { complete: 0, success: 0, error: 0 };
240 * var success = function() { counter.success++ };
241 * var error = function() { counter.error++ };
242 * var complete = function() { counter.complete++ };
243 * $('#foo').ajaxStart(complete).ajaxStop(complete).ajaxComplete(complete).ajaxError(error).ajaxSuccess(success);
244 * // start with successful test
245 * $.ajax({url: "data/name.php", success: success, error: error, complete: function() {
246 * ok( counter.error == 0, 'Check succesful request' );
247 * ok( counter.success == 2, 'Check succesful request' );
248 * ok( counter.complete == 3, 'Check succesful request' );
249 * counter.error = 0; counter.success = 0; counter.complete = 0;
250 * $.ajaxTimeout(500);
251 * $.ajax({url: "data/name.php?wait=5", success: success, error: error, complete: function() {
252 * ok( counter.error == 2, 'Check failed request' );
253 * ok( counter.success == 0, 'Check failed request' );
254 * ok( counter.complete == 3, 'Check failed request' );
259 * @test stop(); var counter = { complete: 0, success: 0, error: 0 };
260 * counter.error = 0; counter.success = 0; counter.complete = 0;
261 * var success = function() { counter.success++ };
262 * var error = function() { counter.error++ };
264 * $.ajax({url: "data/name.php", global: false, success: success, error: error, complete: function() {
265 * ok( counter.error == 0, 'Check sucesful request without globals' );
266 * ok( counter.success == 1, 'Check sucesful request without globals' );
267 * ok( counter.complete == 0, 'Check sucesful request without globals' );
268 * counter.error = 0; counter.success = 0; counter.complete = 0;
269 * $.ajaxTimeout(500);
270 * $.ajax({url: "data/name.php?wait=5", global: false, success: success, error: error, complete: function() {
271 * ok( counter.error == 1, 'Check failed request without globals' );
272 * ok( counter.success == 0, 'Check failed request without globals' );
273 * ok( counter.complete == 0, 'Check failed request without globals' );
278 * @name ajaxHandlersTesting
284 var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(",");
286 for ( var i = 0; i < e.length; i++ ) new function(){
288 jQuery.fn[o] = function(f){
289 return this.bind(o, f);
297 * Load a remote page using an HTTP GET request. All of the arguments to
298 * the method (except URL) are optional.
300 * @example $.get("test.cgi")
302 * @example $.get("test.cgi", { name: "John", time: "2pm" } )
304 * @example $.get("test.cgi", function(data){
305 * alert("Data Loaded: " + data);
308 * @example $.get("test.cgi",
309 * { name: "John", time: "2pm" },
311 * alert("Data Loaded: " + data);
316 * $.get('data/dashboard.xml', function(xml) {
318 * $('tab', xml).each(function() {
319 * content.push($(this).text());
321 * ok( content[0] == 'blabla', 'Check first tab');
322 * ok( content[1] == 'blublu', 'Check second tab');
328 * @param String url The URL of the page to load.
329 * @param Hash params A set of key/value pairs that will be sent to the server.
330 * @param Function callback A function to be executed whenever the data is loaded.
333 get: function( url, data, callback, type, ifModified ) {
334 if ( data && data.constructor == Function ) {
340 // append ? + data or & + data, in case there are already params
341 if ( data ) url += ((url.indexOf("?") > -1) ? "&" : "?") + jQuery.param(data);
343 // Build and start the HTTP Request
346 ifModified: ifModified,
347 complete: function(r, status) {
348 if ( callback ) callback( jQuery.httpData(r,type), status );
354 * Load a remote page using an HTTP GET request, only if it hasn't
355 * been modified since it was last retrieved. All of the arguments to
356 * the method (except URL) are optional.
358 * @example $.getIfModified("test.html")
360 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } )
362 * @example $.getIfModified("test.cgi", function(data){
363 * alert("Data Loaded: " + data);
366 * @example $.getifModified("test.cgi",
367 * { name: "John", time: "2pm" },
369 * alert("Data Loaded: " + data);
374 * $.getIfModified("data/name.php", function(msg) {
375 * ok( msg == 'ERROR', 'Check ifModified' );
379 * @name $.getIfModified
381 * @param String url The URL of the page to load.
382 * @param Hash params A set of key/value pairs that will be sent to the server.
383 * @param Function callback A function to be executed whenever the data is loaded.
386 getIfModified: function( url, data, callback, type ) {
387 jQuery.get(url, data, callback, type, 1);
391 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
392 * All of the arguments to the method (except URL) are optional.
394 * @example $.getScript("test.js")
396 * @example $.getScript("test.js", function(){
397 * alert("Script loaded and executed.");
401 * $.getScript("data/test.js", function() {
402 * ok( foobar == "bar", 'Check if script was evaluated' );
407 * $.getScript("data/test.js");
408 * ok( true, "Check with single argument, can't verify" );
412 * @param String url The URL of the page to load.
413 * @param Function callback A function to be executed whenever the data is loaded.
416 getScript: function( url, callback ) {
418 jQuery.get(url, null, callback, "script");
420 jQuery.get(url, null, null, "script");
425 * Load a remote JSON object using an HTTP GET request.
426 * All of the arguments to the method (except URL) are optional.
428 * @example $.getJSON("test.js", function(json){
429 * alert("JSON Data: " + json.users[3].name);
432 * @example $.getJSON("test.js",
433 * { name: "John", time: "2pm" },
435 * alert("JSON Data: " + json.users[3].name);
440 * $.getJSON("data/json.php", {json: "array"}, function(json) {
441 * ok( json[0].name == 'John', 'Check JSON: first, name' );
442 * ok( json[0].age == 21, 'Check JSON: first, age' );
443 * ok( json[1].name == 'Peter', 'Check JSON: second, name' );
444 * ok( json[1].age == 25, 'Check JSON: second, age' );
448 * $.getJSON("data/json.php", function(json) {
449 * ok( json.data.lang == 'en', 'Check JSON: lang' );
450 * ok( json.data.length == 25, 'Check JSON: length' );
456 * @param String url The URL of the page to load.
457 * @param Hash params A set of key/value pairs that will be sent to the server.
458 * @param Function callback A function to be executed whenever the data is loaded.
461 getJSON: function( url, data, callback ) {
463 jQuery.get(url, data, callback, "json");
465 jQuery.get(url, data, "json");
470 * Load a remote page using an HTTP POST request. All of the arguments to
471 * the method (except URL) are optional.
473 * @example $.post("test.cgi")
475 * @example $.post("test.cgi", { name: "John", time: "2pm" } )
477 * @example $.post("test.cgi", function(data){
478 * alert("Data Loaded: " + data);
481 * @example $.post("test.cgi",
482 * { name: "John", time: "2pm" },
484 * alert("Data Loaded: " + data);
489 * $.post("data/name.php", {xml: "5-2"}, function(xml){
490 * $('math', xml).each(function() {
491 * ok( $('calculation', this).text() == '5-2', 'Check for XML' );
492 * ok( $('result', this).text() == '3', 'Check for XML' );
499 * @param String url The URL of the page to load.
500 * @param Hash params A set of key/value pairs that will be sent to the server.
501 * @param Function callback A function to be executed whenever the data is loaded.
504 post: function( url, data, callback, type ) {
505 // Build and start the HTTP Request
509 data: jQuery.param(data),
510 complete: function(r, status) {
511 if ( callback ) callback( jQuery.httpData(r,type), status );
520 * Set the timeout of all AJAX requests to a specific amount of time.
521 * This will make all future AJAX requests timeout after a specified amount
522 * of time (the default is no timeout).
524 * @example $.ajaxTimeout( 5000 );
525 * @desc Make all AJAX requests timeout after 5 seconds.
530 * $.ajaxTimeout(1000);
531 * var pass = function() {
534 * ok( true, 'Check local and global callbacks after timeout' );
535 * clearTimeout(timeout);
536 * $('#main').unbind("ajaxError");
540 * var fail = function() {
541 * ok( false, 'Check for timeout failed' );
544 * timeout = setTimeout(fail, 1500);
545 * $('#main').ajaxError(pass);
548 * url: "data/name.php?wait=5",
553 * @test stop(); $.ajaxTimeout(50);
557 * url: "data/name.php?wait=1",
558 * error: function() {
559 * ok( false, 'Check for local timeout failed' );
562 * success: function() {
563 * ok( true, 'Check for local timeout' );
571 * @name $.ajaxTimeout
573 * @param Number time How long before an AJAX request times out.
576 ajaxTimeout: function(timeout) {
577 jQuery.timeout = timeout;
580 // Last-Modified header cache for next request
584 * Load a remote page using an HTTP request. This function is the primary
585 * means of making AJAX requests using jQuery. $.ajax() takes one property,
586 * an object of key/value pairs, that're are used to initalize the request.
588 * These are all the key/values that can be passed in to 'prop':
590 * (String) type - The type of request to make (e.g. "POST" or "GET").
592 * (String) url - The URL of the page to request.
594 * (String) data - A string of data to be sent to the server (POST only).
596 * (String) dataType - The type of data that you're expecting back from
597 * the server (e.g. "xml", "html", "script", or "json").
599 * (Boolean) ifModified - Allow the request to be successful only if the
600 * response has changed since the last request, default is false, ignoring
601 * the Last-Modified header
603 * (Number) timeout - Local timeout to override global timeout, eg. to give a
604 * single request a longer timeout while all others timeout after 1 seconds,
607 * (Boolean) global - Wheather to trigger global AJAX event handlers for
608 * this request, default is true. Set to true to prevent that global handlers
609 * like ajaxStart or ajaxStop are triggered.
611 * (Function) error - A function to be called if the request fails. The
612 * function gets passed two arguments: The XMLHttpRequest object and a
613 * string describing the type of error that occurred.
615 * (Function) success - A function to be called if the request succeeds. The
616 * function gets passed one argument: The data returned from the server,
617 * formatted according to the 'dataType' parameter.
619 * (Function) complete - A function to be called when the request finishes. The
620 * function gets passed two arguments: The XMLHttpRequest object and a
621 * string describing the type the success of the request.
628 * @desc Load and execute a JavaScript file.
633 * data: "name=John&location=Boston",
634 * success: function(msg){
635 * alert( "Data Saved: " + msg );
638 * @desc Save some data to the server and notify the user once its complete.
643 * url: "data/name.php?name=foo",
644 * success: function(msg){
645 * ok( msg == 'bar', 'Check for GET' );
653 * url: "data/name.php",
654 * data: "name=peter",
655 * success: function(msg){
656 * ok( msg == 'pan', 'Check for POST' );
662 * window.foobar = undefined;
663 * window.foo = undefined;
664 * var verifyEvaluation = function() {
665 * ok( foobar == "bar", 'Check if script src was evaluated for datatype html' );
670 * url: "data/test.html",
671 * success: function(data) {
672 * ok( data.match(/^html text/), 'Check content for datatype html' );
673 * ok( foo == "foo", 'Check if script was evaluated for datatype html' );
674 * setTimeout(verifyEvaluation, 600);
680 * url: "data/with_fries.xml", dataType: "xml", type: "GET", data: "", success: function(resp) {
681 * ok( $("properties", resp).length == 1, 'properties in responseXML' );
682 * ok( $("jsconf", resp).length == 1, 'jsconf in responseXML' );
683 * ok( $("thing", resp).length == 2, 'things in responseXML' );
690 * @param Hash prop A set of properties to initialize the request with.
693 //ajax: function( type, url, data, ret, ifModified ) {
694 ajax: function( s ) {
696 var fvoid = function() {};
701 timeout: jQuery.timeout,
711 // If only a single argument was passed in,
712 // assume that it is a object of key/value pairs
715 var success = type.success;
716 var error = type.error;
717 var dataType = type.dataType;
718 var global = typeof type.global == "boolean" ? type.global : true;
719 var timeout = typeof type.timeout == "number" ? type.timeout : jQuery.timeout;
720 ifModified = type.ifModified || false;
727 // Watch for a new set of requests
728 if ( s.global && ! jQuery.active++ )
729 jQuery.event.trigger( "ajaxStart" );
731 var requestDone = false;
733 // Create the request object
734 var xml = new XMLHttpRequest();
737 xml.open(s.type, s.url, true);
739 // Set the correct header, if data is being sent
741 xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
743 // Set the If-Modified-Since header, if ifModified mode.
745 xml.setRequestHeader("If-Modified-Since",
746 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
748 // Set header so the called script knows that it's an XMLHttpRequest
749 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
751 // Make sure the browser sends the right content length
752 if ( xml.overrideMimeType )
753 xml.setRequestHeader("Connection", "close");
755 // Wait for a response to come back
756 var onreadystatechange = function(isTimeout){
757 // The transfer is complete and the data is available, or the request timed out
758 if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
761 var status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
762 s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
764 // Make sure that the request was successful or notmodified
765 if ( status != "error" ) {
766 // Cache Last-Modified header, if ifModified mode.
769 modRes = xml.getResponseHeader("Last-Modified");
770 } catch(e) {} // swallow exception thrown by FF if header is not available
772 if ( s.ifModified && modRes )
773 jQuery.lastModified[s.url] = modRes;
775 // If a local callback was specified, fire it
777 s.success( jQuery.httpData( xml, s.dataType ), status );
779 // Fire the global callback
781 jQuery.event.trigger( "ajaxSuccess" );
783 // Otherwise, the request was not successful
785 // If a local callback was specified, fire it
786 if ( s.error ) s.error( xml, status );
788 // Fire the global callback
790 jQuery.event.trigger( "ajaxError" );
793 // The request was completed
795 jQuery.event.trigger( "ajaxComplete" );
797 // Handle the global AJAX counter
798 if ( s.global && ! --jQuery.active )
799 jQuery.event.trigger( "ajaxStop" );
802 if ( s.complete ) s.complete(xml, status);
805 xml.onreadystatechange = function(){};
810 xml.onreadystatechange = onreadystatechange;
814 setTimeout(function(){
815 // Check to see if the request is still happening
817 // Cancel the request
820 if ( !requestDone ) onreadystatechange( "timeout" );
831 // Counter for holding the number of active queries
834 // Determines if an XMLHttpRequest was successful or not
835 httpSuccess: function(r) {
837 return !r.status && location.protocol == "file:" ||
838 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
839 jQuery.browser.safari && r.status == undefined;
845 // Determines if an XMLHttpRequest returns NotModified
846 httpNotModified: function(xml, url) {
848 var xmlRes = xml.getResponseHeader("Last-Modified");
850 // Firefox always returns 200. check Last-Modified date
851 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
852 jQuery.browser.safari && xml.status == undefined;
858 /* Get the data out of an XMLHttpRequest.
859 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
860 * otherwise return plain text.
861 * (String) data - The type of data that you're expecting back,
862 * (e.g. "xml", "html", "script")
864 httpData: function(r,type) {
865 var ct = r.getResponseHeader("content-type");
866 var data = !type && ct && ct.indexOf("xml") >= 0;
867 data = type == "xml" || data ? r.responseXML : r.responseText;
869 // If the type is "script", eval it
870 if ( type == "script" ) eval.call( window, data );
872 // Get the JavaScript object, if JSON is used.
873 if ( type == "json" ) eval( "data = " + data );
875 // evaluate scripts within html
876 if ( type == "html" ) jQuery("<div>").html(data).evalScripts();
881 // Serialize an array of form elements or a set of
882 // key/values into a query string
886 // If an array was passed in, assume that it is an array
888 if ( a.constructor == Array || a.jquery ) {
889 // Serialize the form elements
890 for ( var i = 0; i < a.length; i++ )
891 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
893 // Otherwise, assume that it's an object of key/value pairs
895 // Serialize the key/values
897 s.push( j + "=" + encodeURIComponent( a[j] ) );
900 // Return the resulting serialization