$.ajax
$.ajax(options) ⇒ XMLHttpRequest
Perform an Ajax request. It can be to a local resource, or cross-domain via HTTP access control support in browsers or JSONP.
Options:
type(default: "GET"): HTTP request method ("GET", "POST", or other)url(default: current URL): URL to which the request is madedata(default: none): data for the request; for GET requests it is appended to query string of the URL. Non-string objects will get serialized with $.paramprocessData(default: true): whether to automatically serializedatafor non-GET requests to stringcontentType(default: "application/x-www-form-urlencoded"): the Content-Type of the data being posted to the server (this can also be set viaheaders). Passfalseto skip setting the default value.mimeType(default: none): override the MIME type of the response. v1.1+dataType(default: none): response type to expect from the server. One ofjson,jsonp,script,xml,html, ortext.jsonp(default: "callback"): the name of the JSONP callback query parameterjsonpCallback(default: "jsonp{N}"): the string (or a function that returns) name of the global JSONP callback function. Set this to enable browser caching. v1.1+timeout(default:0): request timeout in milliseconds,0for no timeoutheaders: object of additional HTTP headers for the Ajax requestasync(default: true): set tofalseto issue a synchronous (blocking) requestglobal(default: true): trigger global Ajax events on this requestcontext(default: window): context to execute callbacks intraditional(default: false): activate traditional (shallow) serialization ofdataparameters with $.paramcache(default: true): whether the browser should be allowed to cache GET responses. Since v1.1.4, the default isfalsefordataType: "script"orjsonp.xhrFields(default: none): an object containing properties to be copied over verbatim to the XMLHttpRequest instance. v1.1+username&password(default: none): HTTP Basic authentication credentials. v1.1+
If the URL contains =? or dataType is "jsonp", the request is performed
by injecting a <script> tag instead of using XMLHttpRequest (see JSONP).
This has the limitation of contentType, dataType, headers, and async not
being supported.
Ajax callbacks
You can specify the following callback functions, which are given in order of execution:
-
beforeSend(xhr, settings): before the request is sent. Provides access to the xhr object and allows changing the settings. Returnfalsefrom the function to cancel the request -
success(data, status, xhr): when request succeeds -
error(xhr, errorType, error): if there is an error (timeout, parse error, or status code not in HTTP 2xx) -
complete(xhr, status): after the request is complete, regardless of error or success
Promise callback interface v1.1+
If the optional modules "callbacks" and "deferred" are loaded, the XHR object
returned from $.ajax() calls implements a promise interface for adding
callbacks by chaining:
xhr.done(function(data, status, xhr){ ... })
xhr.fail(function(xhr, errorType, error){ ... })
xhr.always(function(){ ... })
xhr.then(function(){ ... })
These methods supersede the success, error, and complete callback options.
Ajax events
These events are fired during the lifecycle of an Ajax request performed with
the default setting of global: true:
-
ajaxStart(global): fired if no other Ajax requests are currently active -
ajaxBeforeSend(xhr, options): before sending the request; can be cancelled -
ajaxSend(xhr, options): likeajaxBeforeSend, but not cancellable -
ajaxSuccess(xhr, options, data): when the response is success -
ajaxError(xhr, options, error): when there was an error -
ajaxComplete(xhr, options): after request has completed, regardless of error or success -
ajaxStop(global): fired if this was the last active Ajax request
By default, Ajax events are fired on the document object. However, if the
context of a request is a DOM node, the events are fired on that node and will
bubble up the DOM. The only exceptions to this are the global events ajaxStart
& ajaxStop.
$(document).on('ajaxBeforeSend', function(e, xhr, options){
// This gets fired for every Ajax request performed on the page.
// The xhr object and $.ajax() options are available for editing.
// Return false to cancel this request.
})
$.ajax({
type: 'GET',
url: '/projects',
// data to be added to query string:
data: { name: 'Zepto.js' },
// type of data we are expecting in return:
dataType: 'json',
timeout: 300,
context: $('body'),
success: function(data){
// Supposing this JSON payload was received:
// {"project": {"id": 42, "html": "<div>..." }}
// append the HTML to context object.
this.append(data.project.html)
},
error: function(xhr, type){
alert('Ajax error!')
}
})
// post a JSON payload:
$.ajax({
type: 'POST',
url: '/projects',
// post payload:
data: JSON.stringify({ name: 'Zepto.js' }),
contentType: 'application/json'
})