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.
38 * @param String url The URL of the HTML file to load.
39 * @param Object params A set of key/value pairs that will be sent as data to the server.
40 * @param Function callback A function to be executed whenever the data is loaded (parameters: responseText, status and reponse itself).
43 load: function( url, params, callback, ifModified ) {
44 if ( url.constructor == Function )
45 return this.bind("load", url);
47 callback = callback || function(){};
49 // Default to a GET request
52 // If the second parameter was provided
55 if ( params.constructor == Function ) {
56 // We assume that it's the callback
60 // Otherwise, build a param string
62 params = jQuery.param( params );
69 // Request the remote document
74 ifModified: ifModified,
75 complete: function(res, status){
76 if ( status == "success" || !ifModified && status == "notmodified" ) {
77 // Inject the HTML into all the matched elements
78 self.html(res.responseText)
79 // Execute all the scripts inside of the newly-injected HTML
82 .each( callback, [res.responseText, status, res] );
84 callback.apply( self, [res.responseText, status, res] );
91 * Serializes a set of input elements into a string of data.
92 * This will serialize all given elements. If you need
93 * serialization similar to the form submit of a browser,
94 * you should use the form plugin. This is also true for
95 * selects with multiple attribute set, only a single option
98 * @example $("input[@type=text]").serialize();
99 * @before <input type='text' name='name' value='John'/>
100 * <input type='text' name='location' value='Boston'/>
101 * @after name=John&location=Boston
102 * @desc Serialize a selection of input elements to a string
108 serialize: function() {
109 return jQuery.param( this );
113 * Evaluate all script tags inside this jQuery. If they have a src attribute,
114 * the script is loaded, otherwise it's content is evaluated.
121 evalScripts: function() {
122 return this.find('script').each(function(){
124 // for some weird reason, it doesn't work if the callback is ommited
125 jQuery.getScript( this.src );
127 eval.call( window, this.text || this.textContent || this.innerHTML || "" );
133 // If IE is used, create a wrapper for the XMLHttpRequest object
134 if ( jQuery.browser.msie && typeof XMLHttpRequest == "undefined" )
135 XMLHttpRequest = function(){
136 return new ActiveXObject(
137 navigator.userAgent.indexOf("MSIE 5") >= 0 ?
138 "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"
142 // Attach a bunch of functions for handling common AJAX events
145 * Attach a function to be executed whenever an AJAX request begins.
147 * @example $("#loading").ajaxStart(function(){
150 * @desc Show a loading message whenever an AJAX request starts.
154 * @param Function callback The function to execute.
159 * Attach a function to be executed whenever all AJAX requests have ended.
161 * @example $("#loading").ajaxStop(function(){
164 * @desc Hide a loading message after all the AJAX requests have stopped.
168 * @param Function callback The function to execute.
173 * Attach a function to be executed whenever an AJAX request completes.
175 * @example $("#msg").ajaxComplete(function(){
176 * $(this).append("<li>Request Complete.</li>");
178 * @desc Show a message when an AJAX request completes.
182 * @param Function callback The function to execute.
187 * Attach a function to be executed whenever an AJAX request completes
190 * @example $("#msg").ajaxSuccess(function(){
191 * $(this).append("<li>Successful Request!</li>");
193 * @desc Show a message when an AJAX request completes successfully.
197 * @param Function callback The function to execute.
202 * Attach a function to be executed whenever an AJAX request fails.
204 * @example $("#msg").ajaxError(function(){
205 * $(this).append("<li>Error requesting page.</li>");
207 * @desc Show a message when an AJAX request fails.
211 * @param Function callback The function to execute.
216 var e = "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess".split(",");
218 for ( var i = 0; i < e.length; i++ ) new function(){
220 jQuery.fn[o] = function(f){
221 return this.bind(o, f);
229 * Load a remote page using an HTTP GET request. All of the arguments to
230 * the method (except URL) are optional.
232 * @example $.get("test.cgi")
234 * @example $.get("test.cgi", { name: "John", time: "2pm" } )
236 * @example $.get("test.cgi", function(data){
237 * alert("Data Loaded: " + data);
240 * @example $.get("test.cgi",
241 * { name: "John", time: "2pm" },
243 * alert("Data Loaded: " + data);
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 // shift arguments if data argument was ommited
256 if ( data && data.constructor == Function ) {
267 ifModified: ifModified
272 * Load a remote page using an HTTP GET request, only if it hasn't
273 * been modified since it was last retrieved. All of the arguments to
274 * the method (except URL) are optional.
276 * @example $.getIfModified("test.html")
278 * @example $.getIfModified("test.html", { name: "John", time: "2pm" } )
280 * @example $.getIfModified("test.cgi", function(data){
281 * alert("Data Loaded: " + data);
284 * @example $.getifModified("test.cgi",
285 * { name: "John", time: "2pm" },
287 * alert("Data Loaded: " + data);
291 * @name $.getIfModified
293 * @param String url The URL of the page to load.
294 * @param Hash params A set of key/value pairs that will be sent to the server.
295 * @param Function callback A function to be executed whenever the data is loaded.
298 getIfModified: function( url, data, callback, type ) {
299 jQuery.get(url, data, callback, type, 1);
303 * Loads, and executes, a remote JavaScript file using an HTTP GET request.
304 * All of the arguments to the method (except URL) are optional.
306 * @example $.getScript("test.js")
308 * @example $.getScript("test.js", function(){
309 * alert("Script loaded and executed.");
314 * @param String url The URL of the page to load.
315 * @param Function callback A function to be executed whenever the data is loaded.
318 getScript: function( url, callback ) {
320 jQuery.get(url, null, callback, "script");
322 jQuery.get(url, null, null, "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);
343 * @param String url The URL of the page to load.
344 * @param Hash params A set of key/value pairs that will be sent to the server.
345 * @param Function callback A function to be executed whenever the data is loaded.
348 getJSON: function( url, data, callback ) {
349 jQuery.get(url, data, callback, "json");
353 * Load a remote page using an HTTP POST request. All of the arguments to
354 * the method (except URL) are optional.
356 * @example $.post("test.cgi")
358 * @example $.post("test.cgi", { name: "John", time: "2pm" } )
360 * @example $.post("test.cgi", function(data){
361 * alert("Data Loaded: " + data);
364 * @example $.post("test.cgi",
365 * { name: "John", time: "2pm" },
367 * alert("Data Loaded: " + data);
373 * @param String url The URL of the page to load.
374 * @param Hash params A set of key/value pairs that will be sent to the server.
375 * @param Function callback A function to be executed whenever the data is loaded.
378 post: function( url, data, callback, type ) {
393 * Set the timeout of all AJAX requests to a specific amount of time.
394 * This will make all future AJAX requests timeout after a specified amount
395 * of time (the default is no timeout).
397 * @example $.ajaxTimeout( 5000 );
398 * @desc Make all AJAX requests timeout after 5 seconds.
400 * @name $.ajaxTimeout
402 * @param Number time How long before an AJAX request times out.
405 ajaxTimeout: function(timeout) {
406 jQuery.timeout = timeout;
409 // Last-Modified header cache for next request
413 * Load a remote page using an HTTP request. This function is the primary
414 * means of making AJAX requests using jQuery.
416 * $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't
417 * need that object to manipulate directly, but it is available if you need to
418 * abort the request manually.
420 * Please note: Make sure the server sends the right mimetype (eg. xml as
421 * "text/xml"). Sending the wrong mimetype will get you into serious
422 * trouble that jQuery can't solve.
424 * Supported datatypes (see dataType option) are:
426 * "xml": Returns a XML document that can be processed via jQuery.
428 * "html": Returns HTML as plain text, included script tags are evaluated.
430 * "script": Evaluates the response as Javascript and returns it as plain text.
432 * "json": Evaluates the response as JSON and returns a Javascript Object
434 * $.ajax() takes one property, an object of key/value pairs, that are
435 * used to initalize the request. These are all the key/values that can
436 * be passed in to 'prop':
438 * (String) url - The URL of the page to request.
440 * (String) type - The type of request to make (e.g. "POST" or "GET"), default is "GET".
442 * (String) dataType - The type of data that you're expecting back from
443 * the server. No default: If the server sends xml, the responseXML, otherwise
444 * the responseText is is passed to the success callback.
446 * (Boolean) ifModified - Allow the request to be successful only if the
447 * response has changed since the last request, default is false, ignoring
448 * the Last-Modified header
450 * (Number) timeout - Local timeout to override global timeout, eg. to give a
451 * single request a longer timeout while all others timeout after 1 seconds,
452 * see $.ajaxTimeout()
454 * (Boolean) global - Wheather to trigger global AJAX event handlers for
455 * this request, default is true. Set to false to prevent that global handlers
456 * like ajaxStart or ajaxStop are triggered.
458 * (Function) error - A function to be called if the request fails. The
459 * function gets passed two arguments: The XMLHttpRequest object and a
460 * string describing the type of error that occurred.
462 * (Function) success - A function to be called if the request succeeds. The
463 * function gets passed one argument: The data returned from the server,
464 * formatted according to the 'dataType' parameter.
466 * (Function) complete - A function to be called when the request finishes. The
467 * function gets passed two arguments: The XMLHttpRequest object and a
468 * string describing the type the success of the request.
470 * (String) data - Data to be sent to the server. Converted to a query
471 * string, if not already a string. Is appended to the url for GET-requests.
472 * Override processData option to prevent processing.
474 * (String) contentType - When sending data to the server, use this content-type,
475 * default is "application/x-www-form-urlencoded", which is fine for most cases.
477 * (Boolean) processData - By default, data passed in as an object other as string
478 * will be processed and transformed into a query string, fitting to the default
479 * content-type "application/x-www-form-urlencoded". If you want to send DOMDocuments,
480 * set this option to false.
482 * (Boolean) async - By default, all requests are send asynchronous (set to true).
483 * If you need synchronous requests, set this option to false.
490 * @desc Load and execute a JavaScript file.
495 * data: "name=John&location=Boston",
496 * success: function(msg){
497 * alert( "Data Saved: " + msg );
500 * @desc Save some data to the server and notify the user once its complete.
503 * @type XMLHttpRequest
504 * @param Hash prop A set of properties to initialize the request with.
507 ajax: function( s ) {
508 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
513 timeout: jQuery.timeout,
520 contentType: "application/x-www-form-urlencoded",
527 // convert data if not already a string
528 if (s.processData && typeof s.data != 'string')
529 s.data = jQuery.param(s.data);
530 // append data to url for get requests
531 if( s.type.toLowerCase() == "get" )
532 // "?" + data or "&" + data (in case there are already params)
533 s.url += ((s.url.indexOf("?") > -1) ? "&" : "?") + s.data;
536 // Watch for a new set of requests
537 if ( s.global && ! jQuery.active++ )
538 jQuery.event.trigger( "ajaxStart" );
540 var requestDone = false;
542 // Create the request object
543 var xml = new XMLHttpRequest();
546 xml.open(s.type, s.url, s.async);
548 // Set the correct header, if data is being sent
550 xml.setRequestHeader("Content-Type", s.contentType);
552 // Set the If-Modified-Since header, if ifModified mode.
554 xml.setRequestHeader("If-Modified-Since",
555 jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
557 // Set header so the called script knows that it's an XMLHttpRequest
558 xml.setRequestHeader("X-Requested-With", "XMLHttpRequest");
560 // Make sure the browser sends the right content length
561 if ( xml.overrideMimeType )
562 xml.setRequestHeader("Connection", "close");
564 // Wait for a response to come back
565 var onreadystatechange = function(isTimeout){
566 // The transfer is complete and the data is available, or the request timed out
567 if ( xml && (xml.readyState == 4 || isTimeout == "timeout") ) {
570 var status = jQuery.httpSuccess( xml ) && isTimeout != "timeout" ?
571 s.ifModified && jQuery.httpNotModified( xml, s.url ) ? "notmodified" : "success" : "error";
573 // Make sure that the request was successful or notmodified
574 if ( status != "error" ) {
575 // Cache Last-Modified header, if ifModified mode.
578 modRes = xml.getResponseHeader("Last-Modified");
579 } catch(e) {} // swallow exception thrown by FF if header is not available
581 if ( s.ifModified && modRes )
582 jQuery.lastModified[s.url] = modRes;
584 // process the data (runs the xml through httpData regardless of callback)
585 var data = jQuery.httpData( xml, s.dataType );
587 // If a local callback was specified, fire it and pass it the data
589 s.success( data, status );
591 // Fire the global callback
593 jQuery.event.trigger( "ajaxSuccess" );
595 // Otherwise, the request was not successful
597 // If a local callback was specified, fire it
598 if ( s.error ) s.error( xml, status );
600 // Fire the global callback
602 jQuery.event.trigger( "ajaxError" );
605 // The request was completed
607 jQuery.event.trigger( "ajaxComplete" );
609 // Handle the global AJAX counter
610 if ( s.global && ! --jQuery.active )
611 jQuery.event.trigger( "ajaxStop" );
614 if ( s.complete ) s.complete(xml, status);
617 xml.onreadystatechange = function(){};
622 xml.onreadystatechange = onreadystatechange;
626 setTimeout(function(){
627 // Check to see if the request is still happening
629 // Cancel the request
632 if ( !requestDone ) onreadystatechange( "timeout" );
642 // return XMLHttpRequest to allow aborting the request etc.
646 // Counter for holding the number of active queries
649 // Determines if an XMLHttpRequest was successful or not
650 httpSuccess: function(r) {
652 return !r.status && location.protocol == "file:" ||
653 ( r.status >= 200 && r.status < 300 ) || r.status == 304 ||
654 jQuery.browser.safari && r.status == undefined;
660 // Determines if an XMLHttpRequest returns NotModified
661 httpNotModified: function(xml, url) {
663 var xmlRes = xml.getResponseHeader("Last-Modified");
665 // Firefox always returns 200. check Last-Modified date
666 return xml.status == 304 || xmlRes == jQuery.lastModified[url] ||
667 jQuery.browser.safari && xml.status == undefined;
673 /* Get the data out of an XMLHttpRequest.
674 * Return parsed XML if content-type header is "xml" and type is "xml" or omitted,
675 * otherwise return plain text.
676 * (String) data - The type of data that you're expecting back,
677 * (e.g. "xml", "html", "script")
679 httpData: function(r,type) {
680 var ct = r.getResponseHeader("content-type");
681 var data = !type && ct && ct.indexOf("xml") >= 0;
682 data = type == "xml" || data ? r.responseXML : r.responseText;
684 // If the type is "script", eval it´in global context
685 if ( type == "script" ) {
686 if (window.execScript)
687 window.execScript( data );
689 window.setTimeout( data, 0 );
692 // Get the JavaScript object, if JSON is used.
693 if ( type == "json" ) eval( "data = " + data );
695 // evaluate scripts within html
696 if ( type == "html" ) jQuery("<div>").html(data).evalScripts();
701 // Serialize an array of form elements or a set of
702 // key/values into a query string
706 // If an array was passed in, assume that it is an array
708 if ( a.constructor == Array || a.jquery ) {
709 // Serialize the form elements
710 for ( var i = 0; i < a.length; i++ )
711 s.push( a[i].name + "=" + encodeURIComponent( a[i].value ) );
713 // Otherwise, assume that it's an object of key/value pairs
715 // Serialize the key/values
717 //if one value is array then treat each array value in part
718 if (typeof a[j] == 'object') {
719 for (var k = 0; k < a[j].length; k++) {
720 s.push( j + "[]=" + encodeURIComponent( a[j][k] ) );
723 s.push( j + "=" + encodeURIComponent( a[j] ) );
728 // Return the resulting serialization