Permalink
451 lines (440 sloc) 39.8 KB
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="../entries2html.xsl" ?>
<entry type="method" name="jQuery.ajax" return="jqXHR">
<title>jQuery.ajax()</title>
<signature>
<added>1.5</added>
<argument name="url" type="String">
<desc>A string containing the URL to which the request is sent.</desc>
</argument>
<argument name="settings" type="PlainObject" optional="true">
<desc>A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with <a href="/jQuery.ajaxSetup/">$.ajaxSetup()</a>. See <a href="#jQuery-ajax-settings">jQuery.ajax( settings )</a> below for a complete list of all settings.</desc>
</argument>
</signature>
<signature>
<added>1.0</added>
<argument name="settings" type="PlainObject" optional="true">
<desc>A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with <a href="/jQuery.ajaxSetup/">$.ajaxSetup()</a>.</desc>
<property default="depends on DataType" name="accepts" type="PlainObject">
<desc>A set of key/value pairs that map a given <code>dataType</code> to its MIME type, which gets sent in the <code>Accept</code> request header. This header tells the server what kind of response it will accept in return. For example, the following defines a custom type <code>mycustomtype</code> to be sent with the request:
<pre><code>
$.ajax({
accepts: {
mycustomtype: 'application/x-some-custom-type'
},
// Instructions for how to deserialize a `mycustomtype`
converters: {
'text mycustomtype': function(result) {
// Do Stuff
return newresult;
}
},
// Expect a `mycustomtype` back from server
dataType: 'mycustomtype'
});
</code></pre>
<strong>Note:</strong> You will need to specify a complementary entry for this type in <code>converters</code> for this to work properly.
</desc>
</property>
<property default="true" name="async" type="Boolean">
<desc>By default, all requests are sent asynchronously (i.e. this is set to <code>true</code> by default). If you need synchronous requests, set this option to <code>false</code>. Cross-domain requests and <code>dataType: "jsonp"</code> requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. <strong>As of jQuery 1.8</strong>, the use of <code>async: false</code> with jqXHR (<code>$.Deferred</code>) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as <code>jqXHR.done()</code>.</desc>
</property>
<property name="beforeSend" type="Function">
<argument name="jqXHR" type="jqXHR"/>
<argument name="settings" type="PlainObject"/>
<desc>A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an <a href="/Ajax_Events/">Ajax Event</a>. Returning <code>false</code> in the <code>beforeSend</code> function will cancel the request. <strong>As of jQuery 1.5</strong>, the <code>beforeSend</code> option will be called regardless of the type of request.</desc>
</property>
<property name="cache" default="true, false for dataType 'script' and 'jsonp'" type="Boolean">
<desc>If set to <code>false</code>, it will force requested pages not to be cached by the browser. <strong>Note:</strong> Setting <code>cache</code> to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.</desc>
</property>
<property name="complete" type="Function">
<argument name="jqXHR" type="jqXHR"/>
<argument name="textStatus" type="String"/>
<desc>A function to be called when the request finishes (after <code>success</code> and <code>error</code> callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request (<code>"success"</code>, <code>"notmodified"</code>, <code>"nocontent"</code>, <code>"error"</code>, <code>"timeout"</code>, <code>"abort"</code>, or <code>"parsererror"</code>). <strong>As of jQuery 1.5</strong>, the <code>complete</code> setting can accept an array of functions. Each function will be called in turn. This is an <a href="/Ajax_Events/">Ajax Event</a>.</desc>
</property>
<property name="contents" type="PlainObject" added="1.5">
<desc>An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type.</desc>
</property>
<property default="'application/x-www-form-urlencoded; charset=UTF-8'" name="contentType">
<type name="Boolean"/>
<type name="String"/>
<desc>When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to <code>$.ajax()</code>, then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass <code>false</code> to tell jQuery to not set any content type header. <strong>Note:</strong> The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. <strong>Note:</strong> For cross-domain requests, setting the content type to anything other than <code>application/x-www-form-urlencoded</code>, <code>multipart/form-data</code>, or <code>text/plain</code> will trigger the browser to send a preflight OPTIONS request to the server.</desc>
</property>
<property name="context" type="PlainObject">
<desc>This object will be the context of all Ajax-related callbacks. By default, the context is an object that represents the Ajax settings used in the call (<code>$.ajaxSettings</code> merged with the settings passed to <code>$.ajax</code>). For example, specifying a DOM element as the context will make that the context for the <code>complete</code> callback of a request, like so:
<pre><code>
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$( this ).addClass( "done" );
});
</code></pre>
</desc>
</property>
<property name="converters" type="PlainObject" default="{&quot;* text&quot;: window.String, &quot;text html&quot;: true, &quot;text json&quot;: jQuery.parseJSON, &quot;text xml&quot;: jQuery.parseXML}" added="1.5">
<desc>An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response.</desc>
</property>
<property name="crossDomain" type="Boolean" default="false for same-domain requests, true for cross-domain requests" added="1.5">
<desc>If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to <code>true</code>. This allows, for example, server-side redirection to another domain.</desc>
</property>
<property name="data">
<type name="PlainObject"/>
<type name="String"/>
<type name="Array"/>
<desc>Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See <code>processData</code> option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the <code>traditional</code> setting (described below).</desc>
</property>
<property name="dataFilter" type="Function">
<argument name="data" type="String"/>
<argument name="type" type="String"/>
<return type="Anything"/>
<desc>A function to be used to handle the raw response data of XMLHttpRequest. This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter.</desc>
</property>
<property name="dataType" default="Intelligent Guess (xml, json, script, or html)" type="String">
<desc>The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
<ul>
<li><code>"xml"</code>: Returns a XML document that can be processed via jQuery.</li>
<li><code>"html"</code>: Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.</li>
<li><code>"script"</code>: Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, <code>_=[TIMESTAMP]</code>, to the URL unless the <code>cache</code> option is set to <code>true</code>. <strong>Note:</strong> This will turn POSTs into GETs for remote-domain requests.</li>
<li><code>"json"</code>: Evaluates the response as JSON and returns a JavaScript object. Cross-domain <code>"json"</code> requests are converted to <code>"jsonp"</code> unless the request includes <code>jsonp: false</code> in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of <code>null</code> or <code>{}</code> instead. (See <a href="http://json.org/">json.org</a> for more information on proper JSON formatting.)</li>
<li><code>"jsonp"</code>: Loads in a JSON block using <a href="http://bob.ippoli.to/archives/2005/12/05/remote-json-jsonp/">JSONP</a>. Adds an extra <code>"?callback=?"</code> to the end of your URL to specify the callback. Disables caching by appending a query string parameter, <code>"_=[TIMESTAMP]"</code>, to the URL unless the <code>cache</code> option is set to <code>true</code>.</li>
<li><code>"text"</code>: A plain text string.</li>
<li>multiple, space-separated values: <strong>As of jQuery 1.5</strong>, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use <code>"text xml"</code> for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: <code>"jsonp text xml"</code>. Similarly, a shorthand string such as <code>"jsonp xml"</code> will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.</li>
</ul>
</desc>
</property>
<property name="error" type="Function">
<argument name="jqXHR" type="jqXHR"/>
<argument name="textStatus" type="String"/>
<argument name="errorThrown" type="String"/>
<desc>A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides <code>null</code>) are <code>"timeout"</code>, <code>"error"</code>, <code>"abort"</code>, and <code>"parsererror"</code>. When an HTTP error occurs, <code>errorThrown</code> receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." <strong>As of jQuery 1.5</strong>, the <code>error</code> setting can accept an array of functions. Each function will be called in turn. <strong>Note:</strong> <em>This handler is not called for cross-domain script and cross-domain JSONP requests.</em> This is an <a href="/Ajax_Events/">Ajax Event</a>.</desc>
</property>
<property default="true" name="global" type="Boolean">
<desc>Whether to trigger global Ajax event handlers for this request. The default is <code>true</code>. Set to <code>false</code> to prevent the global handlers like <code>ajaxStart</code> or <code>ajaxStop</code> from being triggered. This can be used to control various <a href="/Ajax_Events/">Ajax Events</a>.</desc>
</property>
<property name="headers" type="PlainObject" default="{}" added="1.5">
<desc>An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header <code>X-Requested-With: XMLHttpRequest</code> is always added, but its default <code>XMLHttpRequest</code> value can be changed here. Values in the <code>headers</code> setting can also be overwritten from within the <code>beforeSend</code> function.</desc>
</property>
<property default="false" name="ifModified" type="Boolean">
<desc>Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is <code>false</code>, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data.</desc>
</property>
<property default="depends on current location protocol" name="isLocal" type="Boolean" added="1.5.1">
<desc>Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: <code>file</code>, <code>*-extension</code>, and <code>widget</code>. If the <code>isLocal</code> setting needs modification, it is recommended to do so once in the <code>$.ajaxSetup()</code> method.</desc>
</property>
<property name="jsonp">
<type name="String"/>
<type name="Boolean"/>
<desc>Override the callback function name in a JSONP request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So <code>{jsonp:'onJSONPLoad'}</code> would result in <code>'onJSONPLoad=?'</code> passed to the server. <strong>As of jQuery 1.5</strong>, setting the <code>jsonp</code> option to <code>false</code> prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the <code>jsonpCallback</code> setting. For example, <code>{ jsonp: false, jsonpCallback: "callbackName" }</code>. If you don't trust the target of your Ajax requests, consider setting the <code>jsonp</code> property to <code>false</code> for security reasons.</desc>
</property>
<property name="jsonpCallback">
<type name="String"/>
<type name="Function"/>
<desc>Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. <strong>As of jQuery 1.5</strong>, you can also use a function for this setting, in which case the value of <code>jsonpCallback</code> is set to the return value of that function.</desc>
</property>
<property default="'GET'" name="method" type="String" added="1.9.0">
<desc>The HTTP method to use for the request (e.g. <code>"POST"</code>, <code>"GET"</code>, <code>"PUT"</code>).</desc>
</property>
<property name="mimeType" type="String" added="1.5.1">
<desc>A mime type to override the <abbr title="XMLHttpRequest">XHR</abbr> mime type.</desc>
</property>
<property name="password" type="String">
<desc>A password to be used with XMLHttpRequest in response to an HTTP access authentication request.</desc>
</property>
<property default="true" name="processData" type="Boolean">
<desc>By default, data passed in to the <code>data</code> option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to <code>false</code>.</desc>
</property>
<property name="scriptCharset" type="String">
<desc>Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or "script" dataType and "GET" type). Sets the <code>charset</code> attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script.</desc>
</property>
<property name="statusCode" type="PlainObject" default="{}" added="1.5">
<desc>
<p>An object of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:</p>
<pre><code>
$.ajax({
statusCode: {
404: function() {
alert( "page not found" );
}
}
});
</code></pre>
<p>If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the <code>error</code> callback.</p>
</desc>
</property>
<property name="success" type="Function">
<argument name="data" type="Anything"/>
<argument name="textStatus" type="String"/>
<argument name="jqXHR" type="jqXHR"/>
<desc>A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the <code>dataType</code> parameter or the <code>dataFilter</code> callback function, if specified; a string describing the status; and the <code>jqXHR</code> (in jQuery 1.4.x, XMLHttpRequest) object. <strong>As of jQuery 1.5</strong>, <em>the success setting can accept an array of functions. Each function will be called in turn.</em> This is an <a href="/Ajax_Events/">Ajax Event</a>.</desc>
</property>
<property name="timeout" type="Number">
<desc>Set a timeout (in milliseconds) for the request. This will override any global timeout set with <a href="/jQuery.ajaxSetup/">$.ajaxSetup()</a>. The timeout period starts at the point the <code>$.ajax</code> call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. <strong>In jQuery 1.4.x and below,</strong> the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. <strong>In Firefox 3.0+ only,</strong> script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.</desc>
</property>
<property name="traditional" type="Boolean">
<desc>Set this to <code>true</code> if you wish to use the traditional style of <a href="/jQuery.param/">param serialization</a>.</desc>
</property>
<property default="'GET'" name="type" type="String">
<desc>An alias for <code>method</code>. You should use <code>type</code> if you're using versions of jQuery prior to 1.9.0.</desc>
</property>
<property default="The current page" name="url" type="String">
<desc> A string containing the URL to which the request is sent.</desc>
</property>
<property name="username" type="String">
<desc>A username to be used with XMLHttpRequest in response to an HTTP access authentication request.</desc>
</property>
<property name="xhr" type="Function" default="ActiveXObject when available (IE), the XMLHttpRequest otherwise">
<desc>Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory.</desc>
</property>
<property name="xhrFields" type="PlainObject" added="1.5.1">
<desc>
<p>An object of fieldName-fieldValue pairs to set on the native <code><abbr title="XMLHttpRequest">XHR</abbr></code> object. For example, you can use it to set <code>withCredentials</code> to <code>true</code> for cross-domain requests if needed.</p>
<pre><code>
$.ajax({
url: a_cross_domain_url,
xhrFields: {
withCredentials: true
}
});
</code></pre>
<p><strong>In jQuery 1.5</strong>, the <code>withCredentials</code> property was not propagated to the native <code>XHR</code> and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it.</p>
</desc>
</property>
</argument>
</signature>
<desc>Perform an asynchronous HTTP (Ajax) request.</desc>
<longdesc>
<p>The <code>$.ajax()</code> function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like <code><a href="/jQuery.get/">$.get()</a></code> and <code><a href="/load/">.load()</a></code> are available and are easier to use. If less common options are required, though, <code>$.ajax()</code> can be used more flexibly.</p>
<p>At its simplest, the <code>$.ajax()</code> function can be called with no arguments:</p>
<pre><code>
$.ajax();
</code></pre>
<p><strong>Note:</strong> Default settings can be set globally by using the <code><a href="/jQuery.ajaxSetup/">$.ajaxSetup()</a></code> function.</p>
<p>This example, using no options, loads the contents of the current page, but does nothing with the result. To use the result, you can implement one of the callback functions.</p>
<h4 id="jqXHR">The jqXHR Object</h4>
<p>The jQuery XMLHttpRequest (jqXHR) object returned by <code>$.ajax()</code> <strong>as of jQuery 1.5</strong> is a superset of the browser's native XMLHttpRequest object. For example, it contains <code>responseText</code> and <code>responseXML</code> properties, as well as a <code>getResponseHeader()</code> method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the <code>jqXHR</code> object simulates native XHR functionality where possible. </p>
<p><strong>As of jQuery 1.5.1</strong>, the <code>jqXHR</code> object also contains the <code>overrideMimeType()</code> method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). The <code>.overrideMimeType()</code> method may be used in the <code>beforeSend()</code> callback function, for example, to modify the response content-type header:</p>
<pre><code>
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
})
.done(function( data ) {
if ( console &amp;&amp; console.log ) {
console.log( "Sample of data:", data.slice( 0, 100 ) );
}
});
</code></pre>
<p>The jqXHR objects returned by <code>$.ajax()</code> as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see <a href="/category/deferred-object/">Deferred object</a> for more information). These methods take one or more function arguments that are called when the <code>$.ajax()</code> request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include: </p>
<ul>
<li>
<strong>jqXHR.done(function( data, textStatus, jqXHR ) {});</strong>
<p>An alternative construct to the success callback option, refer to <code><a href="/deferred.done/">deferred.done()</a></code> for implementation details.</p>
</li>
<li>
<strong>jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});</strong>
<p>An alternative construct to the error callback option, the <code>.fail()</code> method replaces the deprecated <code>.error()</code> method. Refer to <code><a href="/deferred.fail/">deferred.fail()</a></code> for implementation details.
</p>
</li>
<li>
<strong>jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });</strong> (added in jQuery 1.6)
<p>An alternative construct to the complete callback option, the <code>.always()</code> method replaces the deprecated <code>.complete()</code> method.</p>
<p>In response to a successful request, the function's arguments are the same as those of <code>.done()</code>: data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of <code>.fail()</code>: the jqXHR object, textStatus, and errorThrown. Refer to <code><a href="/deferred.always/">deferred.always()</a></code> for implementation details.</p>
</li>
<li>
<strong>jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});</strong>
<p>Incorporates the functionality of the <code>.done()</code> and <code>.fail()</code> methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to <a href="/deferred.then/"><code>deferred.then()</code></a> for implementation details.
</p>
</li>
</ul>
<div class="warning">
<p><strong>Deprecation Notice:</strong> The <code>jqXHR.success()</code>, <code>jqXHR.error()</code>, and <code>jqXHR.complete()</code> callbacks are removed as of jQuery 3.0. You can use <code>jqXHR.done()</code>, <code>jqXHR.fail()</code>, and <code>jqXHR.always()</code> instead.</p>
</div>
<pre><code>
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second complete" );
});
</code></pre>
<p>The <code>this</code> reference within all callbacks is the object in the <code>context</code> option passed to <code>$.ajax</code> in the settings; if <code>context</code> is not specified, <code>this</code> is a reference to the Ajax settings themselves.</p>
<p>For backward compatibility with <code>XMLHttpRequest</code>, a <code>jqXHR</code> object will expose the following properties and methods:</p>
<ul>
<li>
<code>readyState</code>
</li>
<li>
<code>status</code>
</li>
<li>
<code>statusText</code>
</li>
<li><code>responseXML</code> and/or <code>responseText</code> when the underlying request responded with xml and/or text, respectively</li>
<li><code>setRequestHeader(name, value)</code> which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one</li>
<li>
<code>getAllResponseHeaders()</code>
</li>
<li>
<code>getResponseHeader()</code>
</li>
<li>
<code>statusCode()</code>
</li>
<li>
<code>abort()</code>
</li>
</ul>
<p>No <code>onreadystatechange</code> mechanism is provided, however, since <code>done</code>, <code>fail</code>, <code>always</code>, and <code>statusCode</code> cover all conceivable requirements.</p>
<h4 id="callback-functions">Callback Function Queues</h4>
<p>The <code>beforeSend</code>, <code>error</code>, <code>dataFilter</code>, <code>success</code> and <code>complete</code> options all accept callback functions that are invoked at the appropriate times.</p>
<p><strong>As of jQuery 1.5</strong>, the <code>fail</code> and <code>done</code>, and, as of jQuery 1.6, <code>always</code> callback hooks are first-in, first-out managed queues, allowing for more than one callback for each hook. See <a href="/category/deferred-object/">Deferred object methods</a>, which are implemented internally for these <code>$.ajax()</code> callback hooks.</p>
<p>The callback hooks provided by <code>$.ajax()</code> are as follows:</p>
<ol>
<li><code>beforeSend</code> callback option is invoked; it receives the <code>jqXHR</code> object and the <code>settings</code> object as parameters.</li>
<li><code>error</code> callback option is invoked, if the request fails. It receives the <code>jqXHR</code>, a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: "abort", "timeout", "No Transport".</li>
<li><code>dataFilter</code> callback option is invoked immediately upon successful receipt of response data. It receives the returned data and the value of <code>dataType</code>, and must return the (possibly altered) data to pass on to <code>success</code>.</li>
<li><code>success</code> callback option is invoked, if the request succeeds. It receives the returned data, a string containing the success code, and the <code>jqXHR</code> object.</li>
<li><strong>Promise callbacks</strong> — <code>.done()</code>, <code>.fail()</code>, <code>.always()</code>, and <code>.then()</code> — are invoked, in the order they are registered. </li>
<li><code>complete</code> callback option fires, when the request finishes, whether in failure or success. It receives the <code>jqXHR</code> object, as well as a string containing the success or error code.</li>
</ol>
<h4 id="data-types">Data Types</h4>
<p>Different types of response to <code>$.ajax()</code> call are subjected to different kinds of pre-processing before being passed to the success handler. The type of pre-processing depends by default upon the Content-Type of the response, but can be set explicitly using the <code>dataType</code> option. If the <code>dataType</code> option is provided, the Content-Type header of the response will be disregarded.</p>
<p>The available data types are <code>text</code>, <code>html</code>, <code>xml</code>, <code>json</code>, <code>jsonp</code>, and <code>script</code>.</p>
<p>If <code>text</code> or <code>html</code> is specified, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the <code>responseText</code> property of the <code>jqXHR</code> object.</p>
<p>If <code>xml</code> is specified, the response is parsed using <a href="/jQuery.parseXML/"><code>jQuery.parseXML</code></a> before being passed, as an <a href="http://api.jquery.com/Types/#XMLDocument"><code>XMLDocument</code></a>, to the success handler. The XML document is made available through the <code>responseXML</code> property of the <code>jqXHR</code> object.</p>
<p>If <code>json</code> is specified, the response is parsed using <a href="/jQuery.parseJSON/"><code>jQuery.parseJSON</code></a> before being passed, as an object, to the success handler. The parsed JSON object is made available through the <code>responseJSON</code> property of the <code>jqXHR</code> object.</p>
<p>If <code>script</code> is specified, <code>$.ajax()</code> will execute the JavaScript that is received from the server before passing it on to the success handler as a string.</p>
<p>If <code>jsonp</code> is specified, <code>$.ajax()</code> will automatically append a query string parameter of (by default) <code>callback=?</code> to the URL. The <code>jsonp</code> and <code>jsonpCallback</code> properties of the settings passed to <code>$.ajax()</code> can be used to specify, respectively, the name of the query string parameter and the name of the JSONP callback function. The server should return valid JavaScript that passes the JSON response into the callback function. <code>$.ajax()</code> will execute the returned JavaScript, calling the JSONP callback function, before passing the JSON object contained in the response to the <code>$.ajax()</code> success handler.</p>
<p>For more information on JSONP, see the <a href="http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/">original post detailing its use</a>.</p>
<h4 id="sending-data-to-server">Sending Data to the Server</h4>
<p>By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the <code>type</code> option. This option affects how the contents of the <code>data</code> option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.</p>
<p>The <code>data</code> option can contain either a query string of the form <code>key1=value1&amp;key2=value2</code>, or an object of the form <code>{key1: 'value1', key2: 'value2'}</code>. If the latter form is used, the data is converted into a query string using <code><a href="/jQuery.param/">jQuery.param()</a></code> before it is sent. This processing can be circumvented by setting <code>processData</code> to <code>false</code>. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the <code>contentType</code> option from <code>application/x-www-form-urlencoded</code> to a more appropriate MIME type.</p>
<h4 id="advanced-options">Advanced Options</h4>
<p>The <code>global</code> option prevents handlers registered using <code><a href="/ajaxSend/">.ajaxSend()</a></code>, <code><a href="/ajaxError/">.ajaxError()</a></code>, and similar methods from firing when this request would trigger them. This can be useful to, for example, suppress a loading indicator that was implemented with <code><a href="/ajaxSend/">.ajaxSend()</a></code> if the requests are frequent and brief. With cross-domain script and JSONP requests, the global option is automatically set to <code>false</code>. See the descriptions of these methods below for more details.</p>
<p>If the server performs HTTP authentication before providing a response, the user name and password pair can be sent via the <code>username</code> and <code>password</code> options.</p>
<p>Ajax requests are time-limited, so errors can be caught and handled to provide a better user experience. Request timeouts are usually either left at their default or set as a global default using <code><a href="/jQuery.ajaxSetup/">$.ajaxSetup()</a></code> rather than being overridden for specific requests with the <code>timeout</code> option.</p>
<p>By default, requests are always issued, but the browser may serve results out of its cache. To disallow use of the cached results, set <code>cache</code> to <code>false</code>. To cause the request to report failure if the asset has not been modified since the last request, set <code>ifModified</code> to <code>true</code>.</p>
<p>The <code>scriptCharset</code> allows the character set to be explicitly specified for requests that use a <code>&lt;script&gt;</code> tag (that is, a type of <code>script</code> or <code>jsonp</code>). This is useful if the script and host page have differing character sets.</p>
<p>The first letter in Ajax stands for "asynchronous," meaning that the operation occurs in parallel and the order of completion is not guaranteed. The <code>async</code> option to <code>$.ajax()</code> defaults to <code>true</code>, indicating that code execution can continue after the request is made. Setting this option to <code>false</code> (and thus making the call no longer asynchronous) is strongly discouraged, as it can cause the browser to become unresponsive.</p>
<p>The <code>$.ajax()</code> function returns the <code>XMLHttpRequest</code> object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the <code>xhr</code> option. The returned object can generally be discarded, but does provide a lower-level interface for observing and manipulating the request. In particular, calling <code>.abort()</code> on the object will halt the request before it completes.</p>
<h4 id="extending-ajax">Extending Ajax</h4>
<p><strong>As of jQuery 1.5</strong>, jQuery's Ajax implementation includes <a href="/jQuery.ajaxPrefilter/">prefilters</a>, <a href="/jQuery.ajaxTransport/">transports</a>, and converters that allow you to extend Ajax with a great deal of flexibility.</p>
<h4 id="using-converters">Using Converters</h4>
<p><code>$.ajax()</code> converters support mapping data types to other data types. If, however, you want to map a custom data type to a known type (e.g <code>json</code>), you must add a correspondence between the response Content-Type and the actual data type using the <code>contents</code> option:</p>
<pre><code>
$.ajaxSetup({
contents: {
mycustomtype: /mycustomtype/
},
converters: {
"mycustomtype json": function( result ) {
// Do stuff
return newresult;
}
}
});
</code></pre>
<p>This extra object is necessary because the response Content-Types and data types never have a strict one-to-one correspondence (hence the regular expression).</p>
<p>To convert from a supported type (e.g <code>text</code>, <code>json</code>) to a custom data type and back again, use another pass-through converter:</p>
<pre><code>
$.ajaxSetup({
contents: {
mycustomtype: /mycustomtype/
},
converters: {
"text mycustomtype": true,
"mycustomtype json": function( result ) {
// Do stuff
return newresult;
}
}
});
</code></pre>
<p>The above now allows passing from <code>text</code> to <code>mycustomtype</code> and then <code>mycustomtype</code> to <code>json</code>.</p>
</longdesc>
<note id="same-origin-policy" type="additional"/>
<note id="same-origin-policy-exceptions" type="additional"/>
<example>
<desc>Save some data to the server and notify the user once it's complete.</desc>
<code><![CDATA[
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
]]></code>
</example>
<example>
<desc>Retrieve the latest version of an HTML page.</desc>
<code><![CDATA[
$.ajax({
url: "test.html",
cache: false
})
.done(function( html ) {
$( "#results" ).append( html );
});
]]></code>
</example>
<example>
<desc>Send an xml document as data to the server. By setting the processData
option to <code>false</code>, the automatic conversion of data to strings is prevented.</desc>
<code><![CDATA[
var xmlDocument = [create xml document];
var xmlRequest = $.ajax({
url: "page.php",
processData: false,
data: xmlDocument
});
xmlRequest.done( handleResponse );
]]></code>
</example>
<example>
<desc>Send an id as data to the server, save some data to the server, and notify the user once it's complete. If the request fails, alert the user.</desc>
<code><![CDATA[
var menuId = $( "ul.nav" ).first().attr( "id" );
var request = $.ajax({
url: "script.php",
method: "POST",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
$( "#log" ).html( msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
]]></code>
</example>
<example>
<desc>Load and execute a JavaScript file.</desc>
<code><![CDATA[
$.ajax({
method: "GET",
url: "test.js",
dataType: "script"
});
]]></code>
</example>
<category slug="ajax/low-level-interface"/>
<category slug="version/1.0"/>
<category slug="version/1.5"/>
<category slug="version/1.5.1"/>
</entry>