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 var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(",");
205 for ( var i = 0; i < e.length; i++ ) new function(){
207 jQuery.fn[o] = function(f){
208 return this.bind(o, f);
216 * Load a remote page using an HTTP GET request. All of the arguments to
217 * the method (except URL) are optional.
219 * @example $.get("test.cgi")
221 * @example $.get("test.cgi", { name: "John", time: "2pm" } )
223 * @example $.get("test.cgi", function(data){
224 * alert("Data Loaded: " + data);
227 * @example $.get("test.cgi",
228 * { name: "John", time: "2pm" },
230 * alert("Data Loaded: " + data);
235 * $.get("data/dashboard.xml", function(xml) {
237 * $('tab', xml).each(function(k) {
238 * // workaround for IE needed here, $(this).text() throws an error
239 * // content[k] = $.trim(this.firstChild.data) || $(this).text();
240 * content[k] = $(this).text();
242 * ok( content[0] && content[0].match(/blabla/), 'Check first tab' );
243 * ok( content[1] && content[1].match(/blublu/), 'Check second tab' );
249 * @param String url The URL of the page to load.
250 * @param Hash params A set of key/value pairs that will be sent to the server.
251 * @param Function callback A function to be executed whenever the data is loaded.
254 get: function( url, data, callback, type, ifModified ) {
255 if ( data.constructor == Function ) {
261 if ( data ) url += "?" + jQuery.param(data);
263 // Build and start the HTTP Request
264 jQuery.ajax( "GET", url, null, function(r, status) {
265 if ( callback ) callback( jQuery.httpData(r,type), status );
270 * Load a remote page using an HTTP GET request, only if it hasn't
271 * been modified since it was last retrieved. All of the arguments to
272 * the method (except URL) are optional.
274 * @example $.getIfModified("test.html")
276 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } )
278 * @example $.getIfModified("test.cgi", function(data){
279 * alert("Data Loaded: " + data);
282 * @example $.getifModified("test.cgi",
283 * { name: "John", time: "2pm" },
285 * alert("Data Loaded: " + data);
289 * @name $.getIfModified
291 * @param String url The URL of the page to load.
292 * @param Hash params A set of key/value pairs that will be sent to the server.
293 * @param Function callback A function to be executed whenever the data is loaded.
296 getIfModified: function( url, data, callback, type ) {
297 jQuery.get(url, data, callback, type, 1);
301 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
302 * All of the arguments to the method (except URL) are optional.
304 * @example $.getScript("test.js")
306 * @example $.getScript("test.js", function(){
307 * alert("Script loaded and executed.");
311 * $.getScript("data/test.js", function() {
312 * ok( foobar == "bar", 'Check if script was evaluated' );
318 * @param String url The URL of the page to load.
319 * @param Function callback A function to be executed whenever the data is loaded.
322 getScript: function( url, callback ) {
323 jQuery.get(url, callback, "script");
327 * Load a remote JSON object using an HTTP GET request.
328 * All of the arguments to the method (except URL) are optional.
330 * @example $.getJSON("test.js", function(json){
331 * alert("JSON Data: " + json.users[3].name);
334 * @example $.getJSON("test.js",
335 * { name: "John", time: "2pm" },
337 * alert("JSON Data: " + json.users[3].name);
342 * $.getJSON("data/json.php", {json: "array"}, function(json) {
343 * ok( json[0].name == 'John', 'Check JSON: first, name' );
344 * ok( json[0].age == 21, 'Check JSON: first, age' );
345 * ok( json[1].name == 'Peter', 'Check JSON: second, name' );
346 * ok( json[1].age == 25, 'Check JSON: second, age' );
350 * $.getJSON("data/json.php", function(json) {
351 * ok( json.data.lang == 'en', 'Check JSON: lang' );
352 * ok( json.data.length == 25, 'Check JSON: length' );
358 * @param String url The URL of the page to load.
359 * @param Hash params A set of key/value pairs that will be sent to the server.
360 * @param Function callback A function to be executed whenever the data is loaded.
363 getJSON: function( url, data, callback ) {
365 jQuery.get(url, data, callback, "json");
367 jQuery.get(url, data, "json");
372 * Load a remote page using an HTTP POST request. All of the arguments to
373 * the method (except URL) are optional.
375 * @example $.post("test.cgi")
377 * @example $.post("test.cgi", { name: "John", time: "2pm" } )
379 * @example $.post("test.cgi", function(data){
380 * alert("Data Loaded: " + data);
383 * @example $.post("test.cgi",
384 * { name: "John", time: "2pm" },
386 * alert("Data Loaded: " + data);
391 * $.post("data/name.php", {xml: "5-2"}, function(xml){
392 * $('math', xml).each(function() {
393 * ok( $('calculation', this).text() == '5-2', 'Check for XML' );
394 * ok( $('result', this).text() == '3', 'Check for XML' );
401 * @param String url The URL of the page to load.
402 * @param Hash params A set of key/value pairs that will be sent to the server.
403 * @param Function callback A function to be executed whenever the data is loaded.
406 post: function( url, data, callback, type ) {
407 // Build and start the HTTP Request
408 jQuery.ajax( "POST", url, jQuery.param(data), function(r, status) {
409 if ( callback ) callback( jQuery.httpData(r,type), status );
417 * Set the timeout of all AJAX requests to a specific amount of time.
418 * This will make all future AJAX requests timeout after a specified amount
419 * of time (the default is no timeout).
421 * @example $.ajaxTimeout( 5000 );
422 * @desc Make all AJAX requests timeout after 5 seconds.
427 * $.ajaxTimeout(1000);
428 * var pass = function() {
431 * ok( true, 'Check local and global callbacks after timeout' );
432 * clearTimeout(timeout);
436 * var fail = function(ba) {
438 * ok( false, 'Check for timeout failed' );
441 * timeout = setTimeout(fail, 1500);
442 * $('#main').ajaxError(pass);
445 * url: "data/name.php?wait=5",
450 * @name $.ajaxTimeout
452 * @param Number time How long before an AJAX request times out.
455 ajaxTimeout: function(timeout) {
456 jQuery.timeout = timeout;
459 // Last-Modified header cache for next request
463 * Load a remote page using an HTTP request. This function is the primary
464 * means of making AJAX requests using jQuery. $.ajax() takes one property,
465 * an object of key/value pairs, that're are used to initalize the request.
467 * These are all the key/values that can be passed in to 'prop':
469 * (String) type - The type of request to make (e.g. "POST" or "GET").
471 * (String) url - The URL of the page to request.
473 * (String) data - A string of data to be sent to the server (POST only).
475 * (String) dataType - The type of data that you're expecting back from
476 * the server (e.g. "xml", "html", "script", or "json").
478 * (Function) error - A function to be called if the request fails. The
479 * function gets passed two arguments: The XMLHttpRequest object and a
480 * string describing the type of error that occurred.
482 * (Function) success - A function to be called if the request succeeds. The
483 * function gets passed one argument: The data returned from the server,
484 * formatted according to the 'dataType' parameter.
486 * (Function) complete - A function to be called when the request finishes. The
487 * function gets passed two arguments: The XMLHttpRequest object and a
488 * string describing the type the success of the request.
495 * @desc Load and execute a JavaScript file.
500 * data: "name=John&location=Boston",
501 * success: function(msg){
502 * alert( "Data Saved: " + msg );
505 * @desc Save some data to the server and notify the user once its complete.
510 * url: "data/name.php?name=foo",
511 * success: function(msg){
512 * ok( msg == 'bar', 'Check for GET' );
520 * url: "data/name.php",
521 * data: "name=peter",
522 * success: function(msg){
523 * ok( msg == 'pan', 'Check for POST' );
530 * @param Hash prop A set of properties to initialize the request with.
533 ajax: function( type, url, data, ret, ifModified ) {
534 // If only a single argument was passed in,
535 // assume that it is a object of key/value pairs
538 var success = type.success;
539 var error = type.error;
540 var dataType = type.dataType;
546 // Watch for a new set of requests
547 if ( ! jQuery.active++ )
548 jQuery.event.trigger( "ajaxStart" );
550 var requestDone = false;
552 // Create the request object
553 var xml = new XMLHttpRequest();
556 xml.open(type || "GET", url, true);
558 // Set the correct header, if data is being sent
560 xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
562 // Set the If-Modified-Since header, if ifModified mode.
564 xml.setRequestHeader("If-Modified-Since",
565 jQuery.lastModified[url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
567 // Set header so the called script knows that it's an XMLHttpRequest
568 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
570 // Make sure the browser sends the right content length
571 if ( xml.overrideMimeType )
572 xml.setRequestHeader("Connection", "close");
574 // Wait for a response to come back
575 var onreadystatechange = function(istimeout){
576 // The transfer is complete and the data is available, or the request timed out
577 if ( xml && (xml.readyState == 4 || istimeout == "timeout") ) {
580 var status = jQuery.httpSuccess( xml ) && istimeout != "timeout" ?
581 ifModified && jQuery.httpNotModified( xml, url ) ? "notmodified" : "success" : "error";
583 // Make sure that the request was successful or notmodified
584 if ( status != "error" ) {
585 // Cache Last-Modified header, if ifModified mode.
586 var modRes = xml.getResponseHeader("Last-Modified");
587 if ( ifModified && modRes ) jQuery.lastModified[url] = modRes;
589 // If a local callback was specified, fire it
591 success( jQuery.httpData( xml, dataType ), status );
593 // Fire the global callback
594 jQuery.event.trigger( "ajaxSuccess" );
596 // Otherwise, the request was not successful
598 // If a local callback was specified, fire it
599 if ( error ) error( xml, status );
601 // Fire the global callback
602 jQuery.event.trigger( "ajaxError" );
605 // The request was completed
606 jQuery.event.trigger( "ajaxComplete" );
608 // Handle the global AJAX counter
609 if ( ! --jQuery.active )
610 jQuery.event.trigger( "ajaxStop" );
613 if ( ret ) ret(xml, status);
616 xml.onreadystatechange = function(){};
621 xml.onreadystatechange = onreadystatechange;
624 if(jQuery.timeout > 0)
625 setTimeout(function(){
626 // Check to see if the request is still happening
628 // Cancel the request
631 if ( !requestDone ) onreadystatechange( "timeout" );
642 // Counter for holding the number of active queries
645 // Determines if an XMLHttpRequest was successful or not
646 httpSuccess: function(r) {
648 return !r.status && location.protocol == "file:" ||
649 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
650 jQuery.browser.safari && r.status == undefined;
656 // Determines if an XMLHttpRequest returns NotModified
657 httpNotModified: function(xml, url) {
659 var xmlRes = xml.getResponseHeader("Last-Modified");
661 // Firefox always returns 200. check Last-Modified date
662 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
663 jQuery.browser.safari && xml.status == undefined;
669 /* Get the data out of an XMLHttpRequest.
670 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
671 * otherwise return plain text.
672 * (String) data - The type of data that you're expecting back,
673 * (e.g. "xml", "html", "script")
675 httpData: function(r,type) {
676 var ct = r.getResponseHeader("content-type");
677 var data = !type && ct && ct.indexOf("xml") >= 0;
678 data = type == "xml" || data ? r.responseXML : r.responseText;
680 // If the type is "script", eval it
681 if ( type == "script" ) eval.call( window, data );
683 // Get the JavaScript object, if JSON is used.
684 if ( type == "json" ) eval( "data = " + data );
689 // Serialize an array of form elements or a set of
690 // key/values into a query string
694 // If an array was passed in, assume that it is an array
696 if ( a.constructor == Array || a.jquery ) {
697 // Serialize the form elements
698 for ( var i = 0; i < a.length; i++ )
699 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
701 // Otherwise, assume that it's an object of key/value pairs
703 // Serialize the key/values
705 s.push( j + "=" + encodeURIComponent( a[j] ) );
708 // Return the resulting serialization