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' );
44 * @param String url The URL of the HTML file to load.
45 * @param Hash params A set of key/value pairs that will be sent to the server.
46 * @param Function callback A function to be executed whenever the data is loaded.
49 load: function( url, params, callback, ifModified ) {
50 if ( url.constructor == Function )
51 return this.bind("load", url);
53 callback = callback || function(){};
55 // Default to a GET request
58 // If the second parameter was provided
61 if ( params.constructor == Function ) {
62 // We assume that it's the callback
66 // Otherwise, build a param string
68 params = jQuery.param( params );
75 // Request the remote document
76 jQuery.ajax( type, url, params,function(res, status){
78 if ( status == "success" || !ifModified && status == "notmodified" ) {
79 // Inject the HTML into all the matched elements
80 self.html(res.responseText).each( callback, [res.responseText, status] );
82 // Execute all the scripts inside of the newly-injected HTML
83 $("script", self).each(function(){
85 $.getScript( this.src );
87 eval.call( window, this.text || this.textContent || this.innerHTML || "" );
90 callback.apply( self, [res.responseText, status] );
98 * A function for serializing a set of input elements into
101 * @example $("input[@type=text]").serialize();
102 * @before <input type='text' name='name' value='John'/>
103 * <input type='text' name='location' value='Boston'/>
104 * @after name=John&location=Boston
105 * @desc Serialize a selection of input elements to a string
107 * @test var data = $(':input').serialize();
108 * ok( data == 'action=Test&text2=Test&radio1=on&radio2=on&check=on&=on&hidden=&foo[bar]=&name=name&button=&=foobar&select1=&select2=3&select3=1', 'Check form serialization as query string' );
114 serialize: function() {
115 return $.param( this );
120 // If IE is used, create a wrapper for the XMLHttpRequest object
121 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
122 XMLHttpRequest = function(){
123 return new ActiveXObject(
124 navigator.userAgent.indexOf("MSIE 5") >= 0 ?
125 "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
129 // Attach a bunch of functions for handling common AJAX events
132 * Attach a function to be executed whenever an AJAX request begins.
134 * @example $("#loading").ajaxStart(function(){
137 * @desc Show a loading message whenever an AJAX request starts.
141 * @param Function callback The function to execute.
146 * Attach a function to be executed whenever all AJAX requests have ended.
148 * @example $("#loading").ajaxStop(function(){
151 * @desc Hide a loading message after all the AJAX requests have stopped.
155 * @param Function callback The function to execute.
160 * Attach a function to be executed whenever an AJAX request completes.
162 * @example $("#msg").ajaxComplete(function(){
163 * $(this).append("<li>Request Complete.</li>");
165 * @desc Show a message when an AJAX request completes.
169 * @param Function callback The function to execute.
174 * Attach a function to be executed whenever an AJAX request completes
177 * @example $("#msg").ajaxSuccess(function(){
178 * $(this).append("<li>Successful Request!</li>");
180 * @desc Show a message when an AJAX request completes successfully.
184 * @param Function callback The function to execute.
189 * Attach a function to be executed whenever an AJAX request fails.
191 * @example $("#msg").ajaxError(function(){
192 * $(this).append("<li>Error requesting page.</li>");
194 * @desc Show a message when an AJAX request fails.
198 * @param Function callback The function to execute.
203 * @test stop(); var counter = { complete: 0, success: 0, error: 0 };
204 * var success = function() { counter.success++ };
205 * var error = function() { counter.error++ };
206 * var complete = function() { counter.complete++ };
207 * $('#foo').ajaxStart(complete).ajaxStop(complete).ajaxComplete(complete).ajaxError(error).ajaxSuccess(success);
208 * // start with successful test
209 * $.ajax({url: "data/name.php", success: success, error: error, complete: function() {
210 * ok( counter.error == 0, 'Check succesful request' );
211 * ok( counter.success == 2, 'Check succesful request' );
212 * ok( counter.complete == 3, 'Check succesful request' );
213 * counter.error = 0; counter.success = 0; counter.complete = 0;
214 * $.ajaxTimeout(500);
215 * $.ajax({url: "data/name.php?wait=5", success: success, error: error, complete: function() {
216 * ok( counter.error == 2, 'Check failed request' );
217 * ok( counter.success == 0, 'Check failed request' );
218 * ok( counter.complete == 3, 'Check failed request' );
219 * counter.error = 0; counter.success = 0; counter.complete = 0;
221 * $.ajax({url: "data/name.php?wait=5", global: false, success: success, error: error, complete: function() {
222 * ok( counter.error == 0, 'Check sucesful request without globals' );
223 * ok( counter.success == 1, 'Check sucesful request without globals' );
224 * ok( counter.complete == 0, 'Check sucesful request without globals' );
225 * counter.error = 0; counter.success = 0; counter.complete = 0;
226 * $.ajaxTimeout(500);
227 * $.ajax({url: "data/name.php?wait=5", global: false, success: success, error: error, complete: function() {
228 * ok( counter.error == 1, 'Check failedrequest without globals' );
229 * ok( counter.success == 0, 'Check failed request without globals' );
230 * ok( counter.complete == 0, 'Check failed request without globals' );
237 * @name ajaxHandlersTesting
243 var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(",");
245 for ( var i = 0; i < e.length; i++ ) new function(){
247 jQuery.fn[o] = function(f){
248 return this.bind(o, f);
256 * Load a remote page using an HTTP GET request. All of the arguments to
257 * the method (except URL) are optional.
259 * @example $.get("test.cgi")
261 * @example $.get("test.cgi", { name: "John", time: "2pm" } )
263 * @example $.get("test.cgi", function(data){
264 * alert("Data Loaded: " + data);
267 * @example $.get("test.cgi",
268 * { name: "John", time: "2pm" },
270 * alert("Data Loaded: " + data);
275 * $.get("data/dashboard.xml", function(xml) {
277 * $('tab', xml).each(function(k) {
278 * // workaround for IE needed here, $(this).text() throws an error
279 * // content[k] = $.trim(this.firstChild.data) || $(this).text();
280 * content[k] = $(this).text();
282 * ok( content[0] && content[0].match(/blabla/), 'Check first tab' );
283 * ok( content[1] && content[1].match(/blublu/), 'Check second tab' );
289 * @param String url The URL of the page to load.
290 * @param Hash params A set of key/value pairs that will be sent to the server.
291 * @param Function callback A function to be executed whenever the data is loaded.
294 get: function( url, data, callback, type, ifModified ) {
295 if ( data.constructor == Function ) {
301 if ( data ) url += "?" + jQuery.param(data);
303 // Build and start the HTTP Request
304 jQuery.ajax( "GET", url, null, function(r, status) {
305 if ( callback ) callback( jQuery.httpData(r,type), status );
310 * Load a remote page using an HTTP GET request, only if it hasn't
311 * been modified since it was last retrieved. All of the arguments to
312 * the method (except URL) are optional.
314 * @example $.getIfModified("test.html")
316 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } )
318 * @example $.getIfModified("test.cgi", function(data){
319 * alert("Data Loaded: " + data);
322 * @example $.getifModified("test.cgi",
323 * { name: "John", time: "2pm" },
325 * alert("Data Loaded: " + data);
330 * $.getIfModified("data/name.php", function(msg) {
331 * ok( msg == 'ERROR', 'Check ifModified' );
335 * @name $.getIfModified
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 getIfModified: function( url, data, callback, type ) {
343 jQuery.get(url, data, callback, type, 1);
347 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
348 * All of the arguments to the method (except URL) are optional.
350 * @example $.getScript("test.js")
352 * @example $.getScript("test.js", function(){
353 * alert("Script loaded and executed.");
357 * $.getScript("data/test.js", function() {
358 * ok( foobar == "bar", 'Check if script was evaluated' );
364 * @param String url The URL of the page to load.
365 * @param Function callback A function to be executed whenever the data is loaded.
368 getScript: function( url, callback ) {
369 jQuery.get(url, callback, "script");
373 * Load a remote JSON object using an HTTP GET request.
374 * All of the arguments to the method (except URL) are optional.
376 * @example $.getJSON("test.js", function(json){
377 * alert("JSON Data: " + json.users[3].name);
380 * @example $.getJSON("test.js",
381 * { name: "John", time: "2pm" },
383 * alert("JSON Data: " + json.users[3].name);
388 * $.getJSON("data/json.php", {json: "array"}, function(json) {
389 * ok( json[0].name == 'John', 'Check JSON: first, name' );
390 * ok( json[0].age == 21, 'Check JSON: first, age' );
391 * ok( json[1].name == 'Peter', 'Check JSON: second, name' );
392 * ok( json[1].age == 25, 'Check JSON: second, age' );
396 * $.getJSON("data/json.php", function(json) {
397 * ok( json.data.lang == 'en', 'Check JSON: lang' );
398 * ok( json.data.length == 25, 'Check JSON: length' );
404 * @param String url The URL of the page to load.
405 * @param Hash params A set of key/value pairs that will be sent to the server.
406 * @param Function callback A function to be executed whenever the data is loaded.
409 getJSON: function( url, data, callback ) {
411 jQuery.get(url, data, callback, "json");
413 jQuery.get(url, data, "json");
418 * Load a remote page using an HTTP POST request. All of the arguments to
419 * the method (except URL) are optional.
421 * @example $.post("test.cgi")
423 * @example $.post("test.cgi", { name: "John", time: "2pm" } )
425 * @example $.post("test.cgi", function(data){
426 * alert("Data Loaded: " + data);
429 * @example $.post("test.cgi",
430 * { name: "John", time: "2pm" },
432 * alert("Data Loaded: " + data);
437 * $.post("data/name.php", {xml: "5-2"}, function(xml){
438 * $('math', xml).each(function() {
439 * ok( $('calculation', this).text() == '5-2', 'Check for XML' );
440 * ok( $('result', this).text() == '3', 'Check for XML' );
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 post: function( url, data, callback, type ) {
453 // Build and start the HTTP Request
454 jQuery.ajax( "POST", url, jQuery.param(data), function(r, status) {
455 if ( callback ) callback( jQuery.httpData(r,type), status );
463 * Set the timeout of all AJAX requests to a specific amount of time.
464 * This will make all future AJAX requests timeout after a specified amount
465 * of time (the default is no timeout).
467 * @example $.ajaxTimeout( 5000 );
468 * @desc Make all AJAX requests timeout after 5 seconds.
473 * $.ajaxTimeout(1000);
474 * var pass = function() {
477 * ok( true, 'Check local and global callbacks after timeout' );
478 * clearTimeout(timeout);
482 * var fail = function() {
483 * ok( false, 'Check for timeout failed' );
486 * timeout = setTimeout(fail, 1500);
487 * $('#main').ajaxError(pass);
490 * url: "data/name.php?wait=5",
495 * @name $.ajaxTimeout
497 * @param Number time How long before an AJAX request times out.
500 ajaxTimeout: function(timeout) {
501 jQuery.timeout = timeout;
504 // Last-Modified header cache for next request
508 * Load a remote page using an HTTP request. This function is the primary
509 * means of making AJAX requests using jQuery. $.ajax() takes one property,
510 * an object of key/value pairs, that're are used to initalize the request.
512 * These are all the key/values that can be passed in to 'prop':
514 * (String) type - The type of request to make (e.g. "POST" or "GET").
516 * (String) url - The URL of the page to request.
518 * (String) data - A string of data to be sent to the server (POST only).
520 * (String) dataType - The type of data that you're expecting back from
521 * the server (e.g. "xml", "html", "script", or "json").
523 * (Boolean) global - Wheather to trigger global AJAX event handlers for
524 * this request, default is true. Set to true to prevent that global handlers
525 * like ajaxStart or ajaxStop are triggered.
527 * (Function) error - A function to be called if the request fails. The
528 * function gets passed two arguments: The XMLHttpRequest object and a
529 * string describing the type of error that occurred.
531 * (Function) success - A function to be called if the request succeeds. The
532 * function gets passed one argument: The data returned from the server,
533 * formatted according to the 'dataType' parameter.
535 * (Function) complete - A function to be called when the request finishes. The
536 * function gets passed two arguments: The XMLHttpRequest object and a
537 * string describing the type the success of the request.
544 * @desc Load and execute a JavaScript file.
549 * data: "name=John&location=Boston",
550 * success: function(msg){
551 * alert( "Data Saved: " + msg );
554 * @desc Save some data to the server and notify the user once its complete.
559 * url: "data/name.php?name=foo",
560 * success: function(msg){
561 * ok( msg == 'bar', 'Check for GET' );
569 * url: "data/name.php",
570 * data: "name=peter",
571 * success: function(msg){
572 * ok( msg == 'pan', 'Check for POST' );
579 * @param Hash prop A set of properties to initialize the request with.
582 ajax: function( type, url, data, ret, ifModified ) {
583 // If only a single argument was passed in,
584 // assume that it is a object of key/value pairs
587 var success = type.success;
588 var error = type.error;
589 var dataType = type.dataType;
590 var global = typeof type.global == "boolean" ? type.global : true;
596 // Watch for a new set of requests
597 if ( global && ! jQuery.active++ )
598 jQuery.event.trigger( "ajaxStart" );
600 var requestDone = false;
602 // Create the request object
603 var xml = new XMLHttpRequest();
606 xml.open(type || "GET", url, true);
608 // Set the correct header, if data is being sent
610 xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
612 // Set the If-Modified-Since header, if ifModified mode.
614 xml.setRequestHeader("If-Modified-Since",
615 jQuery.lastModified[url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
617 // Set header so the called script knows that it's an XMLHttpRequest
618 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
620 // Make sure the browser sends the right content length
621 if ( xml.overrideMimeType )
622 xml.setRequestHeader("Connection", "close");
624 // Wait for a response to come back
625 var onreadystatechange = function(istimeout){
626 // The transfer is complete and the data is available, or the request timed out
627 if ( xml && (xml.readyState == 4 || istimeout == "timeout") ) {
630 var status = jQuery.httpSuccess( xml ) && istimeout != "timeout" ?
631 ifModified && jQuery.httpNotModified( xml, url ) ? "notmodified" : "success" : "error";
633 // Make sure that the request was successful or notmodified
634 if ( status != "error" ) {
635 // Cache Last-Modified header, if ifModified mode.
636 var modRes = xml.getResponseHeader("Last-Modified");
637 if ( ifModified && modRes ) jQuery.lastModified[url] = modRes;
639 // If a local callback was specified, fire it
641 success( jQuery.httpData( xml, dataType ), status );
643 // Fire the global callback
645 jQuery.event.trigger( "ajaxSuccess" );
647 // Otherwise, the request was not successful
649 // If a local callback was specified, fire it
650 if ( error ) error( xml, status );
652 // Fire the global callback
654 jQuery.event.trigger( "ajaxError" );
657 // The request was completed
659 jQuery.event.trigger( "ajaxComplete" );
661 // Handle the global AJAX counter
662 if ( global && ! --jQuery.active )
663 jQuery.event.trigger( "ajaxStop" );
666 if ( ret ) ret(xml, status);
669 xml.onreadystatechange = function(){};
674 xml.onreadystatechange = onreadystatechange;
677 if(jQuery.timeout > 0)
678 setTimeout(function(){
679 // Check to see if the request is still happening
681 // Cancel the request
684 if ( !requestDone ) onreadystatechange( "timeout" );
695 // Counter for holding the number of active queries
698 // Determines if an XMLHttpRequest was successful or not
699 httpSuccess: function(r) {
701 return !r.status && location.protocol == "file:" ||
702 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
703 jQuery.browser.safari && r.status == undefined;
709 // Determines if an XMLHttpRequest returns NotModified
710 httpNotModified: function(xml, url) {
712 var xmlRes = xml.getResponseHeader("Last-Modified");
714 // Firefox always returns 200. check Last-Modified date
715 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
716 jQuery.browser.safari && xml.status == undefined;
722 /* Get the data out of an XMLHttpRequest.
723 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
724 * otherwise return plain text.
725 * (String) data - The type of data that you're expecting back,
726 * (e.g. "xml", "html", "script")
728 httpData: function(r,type) {
729 var ct = r.getResponseHeader("content-type");
730 var data = !type && ct && ct.indexOf("xml") >= 0;
731 data = type == "xml" || data ? r.responseXML : r.responseText;
733 // If the type is "script", eval it
734 if ( type == "script" ) eval.call( window, data );
736 // Get the JavaScript object, if JSON is used.
737 if ( type == "json" ) eval( "data = " + data );
742 // Serialize an array of form elements or a set of
743 // key/values into a query string
747 // If an array was passed in, assume that it is an array
749 if ( a.constructor == Array || a.jquery ) {
750 // Serialize the form elements
751 for ( var i = 0; i < a.length; i++ )
752 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
754 // Otherwise, assume that it's an object of key/value pairs
756 // Serialize the key/values
758 s.push( j + "=" + encodeURIComponent( a[j] ) );
761 // Return the resulting serialization