JQuery - Ajax - JQuery API Documentation

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.

ajax/

Plugins (https://plugins.jquery.com/) Contribute (https://contribute.jquery.org/) Events (https://js.foundation/events)

Support (https://jquery.org/support/) JS Foundation (https://js.foundation/)

Download (https://jquery.com/download/) Search 

API Documentation (https://api.jquery.com/)

Blog (https://blog.jquery.com/)

Plugins (https://plugins.jquery.com/)

Browser Support (https://jquery.com/browser-support/)

jQuery.ajax()
Categories: Ajax (//api.jquery.com/category/ajax/) > Low-Level Interface (//api.jquery.com/
category/ajax/low-level-interface/)

jQuery.ajax( url [, settings ] )


Returns: jqXHR (http://api.jquery.com/Types/#jqXHR)

 jQuery.ajax( url [, settings ] version added: 1.5 (/category/version/1.5/)


)

Type: String (http://api.jquery.com/Types/#String)


A string containing the URL to which the request is sent.

Type: PlainObject (http://api.jquery.com/Types/#PlainObject)


A set of key/value pairs that configure the Ajax request. All settings
are optional. A default can be set for any option with $.ajaxSetup()
(/jQuery.ajaxSetup/). See jQuery.ajax( settings ) below for a
complete list of all settings.

 jQuery.ajax( [settings ] ) version added: 1.0 (/category/version/1.0/)

1 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/

Ajax (// Type: PlainObject (http://api.jquery.com/Types/#PlainObject)


A set of key/value pairs that configure the Ajax request. All settings
api.jquery.com/
are optional. A default can be set for any option with $.ajaxSetup()
category/ajax/)
(/jQuery.ajaxSetup/).
Global Ajax Event
(default: depend on dataTpe )
Handlers (//
Type: PlainObject (http://api.jquery.com/Types/#PlainObject)
api.jquery.com/ A set of key/value pairs that map a given dataTpe to its
category/ajax/ MIME type, which gets sent in the Accept request header.
global-ajax-event- This header tells the server what kind of response it will
handlers/) accept in return. For example, the following defines a custom
type mcutomtpe to be sent with the request:
Helper Functions
(//api.jquery.com/
1 $.ajax({
category/ajax/ 2 accept: {
helper-functions/) 3 mcutomtpe: 'application/x-ome-cutom-tpe'
4 },
Low-Level 5
Interface (// 6 // Intruction for how to deerialize a `mcut
7 converter: {
api.jquery.com/ 8 'text mcutomtpe': function(reult
category/ajax/low- 9 // Do tuff
level-interface/) 10 return newreult;
11 }
Shorthand 12 },
13
Methods (// 14 // xpect a `mcutomtpe` ack from erver
api.jquery.com/ 15 dataTpe: 'mcutomtpe'
category/ajax/ 16 });
shorthand-
methods/) You will need to specify a complementary entry for this
type in converter for this to work properly.

Attributes (// (default: true )


api.jquery.com/ Type: Boolean (http://api.jquery.com/Types/#Boolean)
category/attributes/) By default, all requests are sent asynchronously (i.e. this is
set to true by default). If you need synchronous requests,
Callbacks Object (// set this option to fale . Cross-domain requests and
api.jquery.com/ dataTpe: "jonp" requests do not support synchronous
category/callbacks- operation. Note that synchronous requests may temporarily
object/) lock the browser, disabling any actions while the request is
active. , the use of anc: fale with
Core (// jqXHR ( $.Deferred ) is deprecated; you must use the
api.jquery.com/ success/error/complete callback options instead of the
category/core/) corresponding methods of the jqXHR object such as
jqXHR.done() .
CSS (//
api.jquery.com/
category/css/) Type: Function (http://api.jquery.com/Types/#Function)(
Data (// jqXHR (http://api.jquery.com/Types/#jqXHR) jqXHR,
PlainObject (http://api.jquery.com/Types/#PlainObject)
api.jquery.com/
settings )
category/data/)
A pre-request callback function that can be used to modify

2 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/

Deferred Object (// the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before
it is sent. Use this to set custom headers, etc. The jqXHR and
api.jquery.com/
settings objects are passed as arguments. This is an Ajax
category/deferred-
Event (/Ajax_Events/). Returning fale in the eforeend
object/) function will cancel the request. , the
Deprecated (// eforeend option will be called regardless of the type of
request.
api.jquery.com/
category/
(default: true, fale for dataTpe 'cript' and
deprecated/) 'jonp' )
Deprecated 1.3 (// Type: Boolean (http://api.jquery.com/Types/#Boolean)
api.jquery.com/ If set to fale , it will force requested pages not to be
category/ cached by the browser. Setting cache to false will only
work correctly with HEAD and GET requests. It works by
deprecated/
appending "_={timestamp}" to the GET parameters. The
deprecated-1.3/)
parameter is not needed for other types of requests, except
Deprecated 1.7 (// in IE8 when a POST is made to a URL that has already been
api.jquery.com/ requested by a GET.
category/
deprecated/
Type: Function (http://api.jquery.com/Types/#Function)(
deprecated-1.7/)
jqXHR (http://api.jquery.com/Types/#jqXHR) jqXHR, String
Deprecated 1.8 (// (http://api.jquery.com/Types/#String) textStatus )
api.jquery.com/ A function to be called when the request finishes (after
ucce and error callbacks are executed). The function
category/
gets passed two arguments: The jqXHR (in jQuery 1.4.x,
deprecated/
XMLHTTPRequest) object and a string categorizing the
deprecated-1.8/) status of the request ( "ucce" , "notmodified" ,
"nocontent" , "error" , "timeout" , "aort" , or
Deprecated 1.9 (//
"parererror" ). , the complete setting can
api.jquery.com/
accept an array of functions. Each function will be called in
category/
turn. This is an Ajax Event (/Ajax_Events/).
deprecated/
deprecated-1.9/)
Type: PlainObject (http://api.jquery.com/Types/#PlainObject)
Deprecated 1.10
An object of string/regular-expression pairs that determine
(//api.jquery.com/
how jQuery will parse the response, given its content type.
category/
deprecated/
deprecated-1.10- (default: 'application/x-www-form-
and-2.0/) urlencoded; charet=UTF-8' )
Type: Boolean (http://api.jquery.com/Types/#Boolean) or
Deprecated 3.0 (// String (http://api.jquery.com/Types/#String)
api.jquery.com/ When sending data to the server, use this content type.
category/ Default is "application/x-www-form-urlencoded;
deprecated/ charset=UTF-8", which is fine for most cases. If you explicitly
deprecated-3.0/) pass in a content-type to $.ajax() , then it is always sent to
the server (even if no data is sent). As of jQuery 1.6 you can
Deprecated 3.2 (// pass fale to tell jQuery to not set any content type header.
api.jquery.com/ The W3C XMLHttpRequest specification dictates that
category/ the charset is always UTF-8; specifying another charset will

3 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/
deprecated/ not force the browser to change the encoding. For
deprecated-3.2/) cross-domain requests, setting the content type to anything
other than application/x-www-form-urlencoded ,
Deprecated 3.3 (// multipart/form-data , or text/plain will trigger the
api.jquery.com/ browser to send a preflight OPTIONS request to the server.
category/
deprecated/
deprecated-3.3/) Type: PlainObject (http://api.jquery.com/Types/#PlainObject)
This object will be the context of all Ajax-related callbacks.
Deprecated 3.4 (// By default, the context is an object that represents the Ajax
api.jquery.com/ settings used in the call ( $.ajaxetting merged with the
category/ settings passed to $.ajax ). For example, specifying a DOM
deprecated/ element as the context will make that the context for the
complete callback of a request, like so:
deprecated-3.4/)

Deprecated 3.5 (//


1 $.ajax({
api.jquery.com/ 2 url: "tet.html",
category/ 3 context: document.od
4 }).done(function() {
deprecated/ 5 $( thi ).addCla( "done" );
deprecated-3.5/) 6 });

Dimensions (//
api.jquery.com/ (default: {"* text": window.tring, "text
html": true, "text jon": jQuer.pareJON, "text
category/
xml": jQuer.pareXML} )
dimensions/)
Type: PlainObject (http://api.jquery.com/Types/#PlainObject)
Effects (// An object containing dataType-to-dataType converters. Each
api.jquery.com/ converter's value is a function that returns the transformed
category/effects/) value of the response.

Basics (//
api.jquery.com/ (default: fale for ame-domain requet,
category/effects/ true for cro-domain requet )
basics/) Type: Boolean (http://api.jquery.com/Types/#Boolean)
If you wish to force a crossDomain request (such as JSONP)
Custom (// on the same domain, set the value of crossDomain to true .
api.jquery.com/ This allows, for example, server-side redirection to another
category/effects/ domain.
custom-effects/)

Fading (// Type: PlainObject (http://api.jquery.com/Types/#PlainObject)


api.jquery.com/ or String (http://api.jquery.com/Types/#String) or Array
category/effects/ (http://api.jquery.com/Types/#Array)
fading/) Data to be sent to the server. If the HTTP method is one that
cannot have an entity body, such as GET, the data is
Sliding (// appended to the URL.
api.jquery.com/
category/effects/ When data is an object, jQuery generates the data string
sliding/) from the object's key/value pairs unless the proceData
option is set to fale . For example, { a: "c", d: "e,f"

4 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/

Events (// } is converted to the string "a=c&d=e%2Cf" . If the value is


an array, jQuery serializes multiple values with same key
api.jquery.com/
based on the value of the traditional setting (described
category/events/)
below). For example, { a: [1,2] } becomes the string
Browser Events (// "a%5%5D=1&a%5%5D=2" with the default traditional:
api.jquery.com/ fale setting.
category/events/
When data is passed as a string it should
browser-events/)
using the correct encoding for contentTpe , which
Document Loading by default is application/x-www-form-urlencoded .
(//api.jquery.com/
In requests with dataTpe: "jon" or dataTpe: "jonp" ,
category/events/ if the string contains a double question mark ( ?? ) anywhere
document- in the URL or a single question mark ( ? ) in the query string, it
loading/) is replaced with a value generated by jQuery that is unique
for each copy of the library on the page (e.g.
Event Handler
jQuer21406515378922229067_1479880736745 ).
Attachment (//
api.jquery.com/
category/events/
event-handler- Type: Function (http://api.jquery.com/Types/#Function)(
String (http://api.jquery.com/Types/#String) data, String
attachment/)
(http://api.jquery.com/Types/#String) type ) => Anything
Event Object (// (http://api.jquery.com/Types/#Anything)
api.jquery.com/ A function to be used to handle the raw response data of
category/events/ XMLHttpRequest. This is a pre-filtering function to sanitize
the response. You should return the sanitized data. The
event-object/)
function accepts two arguments: The raw data returned from
Form Events (// the server and the 'dataType' parameter.
api.jquery.com/
category/events/ (default: Intelligent Gue (xml, jon,
cript, or html) )
form-events/)
Type: String (http://api.jquery.com/Types/#String)
Keyboard Events The type of data that you're expecting back from the server. If
(//api.jquery.com/ none is specified, jQuery will try to infer it based on the MIME
category/events/ type of the response (an XML MIME type will yield XML, in
keyboard-events/) 1.4 JSON will yield a JavaScript object, in 1.4 script will
execute the script, and anything else will be returned as a
Mouse Events (// string). The available types (and the result passed as the first
api.jquery.com/ argument to your success callback) are:
category/events/ "xml" : Returns a XML document that can be
mouse-events/) processed via jQuery.

"html" : Returns HTML as plain text; included script


Forms (//
tags are evaluated when inserted in the DOM.
api.jquery.com/
category/forms/) "cript" : Evaluates the response as JavaScript and

Internals (// returns it as plain text. Disables caching by appending


a query string parameter, _=[TIMTAMP] , to the URL
api.jquery.com/
unless the cache option is set to true . This will
category/internals/)
turn POSTs into GETs for remote-domain requests.

5 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/

Manipulation (// Prior to jQuery 3.5.0, unsuccessful HTTP responses


with a script Content-Tpe were still executed.
api.jquery.com/
category/
"jon" : Evaluates the response as JSON and returns
manipulation/) a JavaScript object. Cross-domain "jon" requests
Class Attribute (// that have a callback placeholder, e.g. ?callack=? ,
api.jquery.com/ are performed using JSONP (https://bob.ippoli.to/
category/ archives/2005/12/05/remote-json-jsonp/) unless the
request includes jonp: fale in its request options.
manipulation/
The JSON data is parsed in a strict manner; any
class-attribute/)
malformed JSON is rejected and a parse error is
Copying (// thrown. As of jQuery 1.9, an empty response is also
api.jquery.com/ rejected; the server should return a response of null
or {} instead. (See json.org (https://json.org/) for
category/
more information on proper JSON formatting.)
manipulation/
copying/)
"jonp" : Loads in a JSON block using JSONP
DOM Insertion, (https://bob.ippoli.to/archives/2005/12/05/remote-
Around (// json-jsonp/). Adds an extra "?callack=?" to the end
of your URL to specify the callback. Disables caching
api.jquery.com/
by appending a query string parameter,
category/
"_=[TIMTAMP]" , to the URL unless the cache option
manipulation/ is set to true .
dom-insertion-
around/) "text" : A plain text string.

DOM Insertion,
multiple, space-separated values: ,
Inside (// jQuery can convert a dataType from what it received in
api.jquery.com/ the Content-Type header to what you require. For
category/ example, if you want a text response to be treated as
manipulation/ XML, use "text xml" for the dataType. You can also
dom-insertion- make a JSONP request, have it received as text, and
inside/) interpreted by jQuery as XML: "jonp text xml" .
Similarly, a shorthand string such as "jonp xml" will
DOM Insertion, first attempt to convert from jsonp to xml, and, failing
Outside (// that, convert from jsonp to text, and then from text to
api.jquery.com/ xml.
category/
manipulation/
dom-insertion- Type: Function (http://api.jquery.com/Types/#Function)(
outside/) jqXHR (http://api.jquery.com/Types/#jqXHR) jqXHR, String
(http://api.jquery.com/Types/#String) textStatus, String
DOM Removal (// (http://api.jquery.com/Types/#String) errorThrown )
api.jquery.com/ A function to be called if the request fails. The function
category/ receives three arguments: The jqXHR (in jQuery 1.4.x,
manipulation/ XMLHttpRequest) object, a string describing the type of error
dom-removal/) that occurred and an optional exception object, if one
occurred. Possible values for the second argument (besides
DOM Replacement null ) are "timeout" , "error" , "aort" , and
(//api.jquery.com/ "parererror" . When an HTTP error occurs, errorThrown
receives the textual portion of the HTTP status, such as "Not
6 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/
category/ Found" or "Internal Server Error." (in HTTP/2 it may instead be
manipulation/ an empty string) , the error setting can
dom- accept an array of functions. Each function will be called in
turn.
replacement/)
This is an Ajax Event (/
General Attributes Ajax_Events/).
(//api.jquery.com/
category/ (default: true )
Type: Boolean (http://api.jquery.com/Types/#Boolean)
manipulation/
Whether to trigger global Ajax event handlers for this
general-
request. The default is true . Set to fale to prevent the
attributes/) global handlers like ajaxtart or ajaxtop from being
Style Properties (// triggered. This can be used to control various Ajax Events (/
Ajax_Events/).
api.jquery.com/
category/
(default: {} )
manipulation/
Type: PlainObject (http://api.jquery.com/Types/#PlainObject)
style-properties/) An object of additional header key/value pairs to send along
with requests using the XMLHttpRequest transport. The
Miscellaneous (// header X-Requeted-With: XMLHttpRequet is always
added, but its default XMLHttpRequet value can be
api.jquery.com/
changed here. Values in the header setting can also be
category/
overwritten from within the eforeend function.
miscellaneous/)
Collection
Manipulation (// (default: fale )
api.jquery.com/ Type: Boolean (http://api.jquery.com/Types/#Boolean)
Allow the request to be successful only if the response has
category/
changed since the last request. This is done by checking the
miscellaneous/
Last-Modified header. Default value is fale , ignoring the
collection- header. In jQuery 1.4 this technique also checks the 'etag'
manipulation/) specified by the server to catch unmodified data.
Data Storage (//
(default: depend on current location protocol )
api.jquery.com/
Type: Boolean (http://api.jquery.com/Types/#Boolean)
category/ Allow the current environment to be recognized as "local,"
miscellaneous/ (e.g. the filesystem), even if jQuery does not recognize it as
data-storage/) such by default. The following protocols are currently
recognized as local: file , *-extenion , and widget . If the
DOM Element
iLocal setting needs modification, it is recommended to
Methods (// do so once in the $.ajaxetup() method.
api.jquery.com/
category/
miscellaneous/
dom-element- Type: String (http://api.jquery.com/Types/#String) or Boolean
methods/) (http://api.jquery.com/Types/#Boolean)
Override the callback function name in a JSONP request.
Setup Methods (// This value will be used instead of 'callback' in the 'callback=?'
api.jquery.com/ part of the query string in the url. So
category/ {jonp:'onJONPLoad'} would result in 'onJONPLoad=?'
miscellaneous/ passed to the server. , setting the jonp

7 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/
setup-methods/) option to fale 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
Offset (// jonpCallack setting. For example, { jonp: fale,
api.jquery.com/ jonpCallack: "callackName" } . If you don't trust the
category/offset/) target of your Ajax requests, consider setting the jonp
property to fale for security reasons.
Properties (//
api.jquery.com/
category/properties/) Type: String (http://api.jquery.com/Types/#String) or
Properties of Function (http://api.jquery.com/Types/#Function)()
jQuery Object Specify the callback function name for a JSONP request.
This value will be used instead of the random name
Instances (//
automatically generated by jQuery. It is preferable to let
api.jquery.com/
jQuery generate a unique name as it'll make it easier to
category/ manage the requests and provide callbacks and error
properties/jquery- handling. You may want to specify the callback when you
object-instance- want to enable better browser caching of GET requests.
properties/) , you can also use a function for this setting, in
which case the value of jonpCallack is set to the return
Properties of the value of that function.
Global jQuery
Object (// (default: 'GT' )
api.jquery.com/ Type: String (http://api.jquery.com/Types/#String)
category/ The HTTP method to use for the request (e.g. "POT" ,
properties/global- "GT" , "PUT" ).

jquery-object-
properties/)

Type: String (http://api.jquery.com/Types/#String)


Removed (// A mime type to override the XHR (XMLHttpRequest) mime
api.jquery.com/ type.
category/removed/)

Selectors (// Type: String (http://api.jquery.com/Types/#String)


api.jquery.com/ A password to be used with XMLHttpRequest in response to
category/selectors/) an HTTP access authentication request.

Attribute (//
(default: true )
api.jquery.com/ Type: Boolean (http://api.jquery.com/Types/#Boolean)
category/ By default, data passed in to the data option as an object
selectors/ (technically, anything other than a string) will be processed
attribute- and transformed into a query string, fitting to the default
selectors/) content-type "application/x-www-form-urlencoded". If you
want to send a DOMDocument, or other non-processed data,
Basic (// set this option to fale .
api.jquery.com/
category/
selectors/basic- Type: PlainObject (http://api.jquery.com/Types/#PlainObject)
css-selectors/) Defines an object with additional attributes to be used in a
"script" or "jsonp" request. The key represents the name of

8 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/

Basic Filter (// the attribute and the value is the attribute's value. If this
object is provided it will force the use of a script-tag
api.jquery.com/
transport. For example, this can be used to set nonce ,
category/
integrit , or croorigin attributes to satisfy Content
selectors/basic- Security Policy requirements.
filter-selectors/)

Child Filter (//


api.jquery.com/
Type: String (http://api.jquery.com/Types/#String)
category/ Only applies when the "script" transport is used. Sets the
selectors/child- charet attribute on the script tag used in the request. Used
filter-selectors/) when the character set on the local page is not the same as
the one on the remote script. Alternatively, the charet
Content Filter (//
attribute can be specified in criptAttr instead, which will
api.jquery.com/ also ensure the use of the "script" transport.
category/
selectors/content- (default: {} )
filter-selector/) Type: PlainObject (http://api.jquery.com/Types/#PlainObject)
An object of numeric HTTP codes and functions to be called
Form (//
when the response has the corresponding code. For
api.jquery.com/ example, the following will alert when the response status is
category/ a 404:
selectors/form-
selectors/) 1 $.ajax({
2 tatuCode: {
Hierarchy (// 3 404: function() {
api.jquery.com/ 4 alert( "page not found" );
category/ 5 }
6 }
selectors/ 7 });
hierarchy-
selectors/)
If the request is successful, the status code functions take
jQuery Extensions the same parameters as the success callback; if it results in
(//api.jquery.com/ an error (including 3xx redirect), they take the same
parameters as the error callback.
category/
selectors/jquery-
selector-
extensions/)
Type: Function (http://api.jquery.com/Types/#Function)(
Visibility Filter (//
Anything (http://api.jquery.com/Types/#Anything) data,
api.jquery.com/ String (http://api.jquery.com/Types/#String) textStatus,
category/ jqXHR (http://api.jquery.com/Types/#jqXHR) jqXHR )
selectors/visibility- A function to be called if the request succeeds. The function
filter-selectors/) gets passed three arguments: The data returned from the
server, formatted according to the dataTpe parameter or
the dataFilter callback function, if specified; a string
Traversing (// describing the status; and the jqXHR (in jQuery 1.4.x,
api.jquery.com/ XMLHttpRequest) object. ,
category/traversing/)
Filtering (// This is an Ajax Event (/Ajax_Events/).

9 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/
api.jquery.com/
category/ Type: Number (http://api.jquery.com/Types/#Number)
traversing/ Set a timeout (in milliseconds) for the request. A value of 0
filtering/) means there will be no timeout. This will override any global
timeout set with $.ajaxSetup() (/jQuery.ajaxSetup/). The
Miscellaneous
timeout period starts at the point the $.ajax call is made; if
Traversing (// several other requests are in progress and the browser has
api.jquery.com/ no connections available, it is possible for a request to time
category/ out before it can be sent. the
traversing/ XMLHttpRequest object will be in an invalid state if the
miscellaneous- request times out; accessing any object members may throw
traversal/) an exception. script and JSONP
requests cannot be cancelled by a timeout; the script will run
Tree Traversal (// even if it arrives after the timeout period.
api.jquery.com/
category/
traversing/tree- Type: Boolean (http://api.jquery.com/Types/#Boolean)
traversal/) Set this to true if you wish to use the traditional style of
param serialization (/jQuery.param/).

Utilities (// (default: 'GT' )


api.jquery.com/ Type: String (http://api.jquery.com/Types/#String)
category/utilities/) An alias for method . You should use tpe if you're using
versions of jQuery prior to 1.9.0.
Version (//
api.jquery.com/ (default: The current page )
category/version/) Type: String (http://api.jquery.com/Types/#String)
A string containing the URL to which the request is sent.
Version 1.0 (//
api.jquery.com/
category/version/ Type: String (http://api.jquery.com/Types/#String)
1.0/) A username to be used with XMLHttpRequest in response to
an HTTP access authentication request.
Version 1.0.4 (//
api.jquery.com/
(default: ActiveXOject when availale (I), the
category/version/
XMLHttpRequet otherwie )
1.0.4/) Type: Function (http://api.jquery.com/Types/#Function)()
Version 1.1 (// Callback for creating the XMLHttpRequest object. Defaults to
the ActiveXObject when available (IE), the XMLHttpRequest
api.jquery.com/
otherwise. Override to provide your own implementation for
category/version/
XMLHttpRequest or enhancements to the factory.
1.1/)

Version 1.1.2 (//


Type: PlainObject (http://api.jquery.com/Types/#PlainObject)
api.jquery.com/
An object of fieldName-fieldValue pairs to set on the native
category/version/
XHR (XMLHttpRequet) object. For example, you can use it
1.1.2/) to set withCredential to true for cross-domain requests
Version 1.1.3 (// if needed.
api.jquery.com/
category/version/

10 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/
1.1.3/) 1 $.ajax({
2 url: a_cro_domain_url,
Version 1.1.4 (// 3 xhrField: {
4 withCredential: true
api.jquery.com/
5 }
category/version/ 6 });
1.1.4/)

Version 1.2 (// , the withCredential property was not


api.jquery.com/ propagated to the native XHR and thus CORS requests
requiring it would ignore this flag. For this reason, we
category/version/
recommend using jQuery 1.5.1+ should you require the use
1.2/)
of it.
Version 1.2.3 (//
api.jquery.com/
category/version/
1.2.3/) The $.ajax() function underlies all Ajax requests sent by jQuery. It is
often unnecessary to directly call this function, as several higher-level
Version 1.2.6 (//
alternatives like $.get() (/jQuer.get/) and .load() (/load/) are
api.jquery.com/
available and are easier to use. If less common options are required,
category/version/
though, $.ajax() can be used more flexibly.
1.2.6/)

Version 1.3 (// At its simplest, the $.ajax() function can be called with no arguments:
api.jquery.com/
category/version/ 1 $.ajax();
1.3/)

Version 1.4 (// Default settings can be set globally by using the $.ajaxetup()
api.jquery.com/ (/jQuer.ajaxetup/) function.

category/version/
This example, using no options, loads the contents of the current page,
1.4/)
but does nothing with the result. To use the result, you can implement
Version 1.4.1 (// one of the callback functions.
api.jquery.com/
category/version/ The jqXHR Object
1.4.1/)
The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax()
Version 1.4.2 (// is a superset of the browser's native XMLHttpRequest object.
api.jquery.com/ For example, it contains reponeText and reponeXML properties, as
category/version/ well as a getReponeHeader() method. When the transport mechanism
1.4.2/) is something other than XMLHttpRequest (for example, a script tag for a
JSONP request) the jqXHR object simulates native XHR functionality
Version 1.4.3 (//
where possible.
api.jquery.com/
category/version/ , the jqXHR object also contains the
1.4.3/) overrideMimeTpe() method (it was available in jQuery 1.4.x, as well,

Version 1.4.4 (// but was temporarily removed in jQuery 1.5). The .overrideMimeTpe()
api.jquery.com/ method may be used in the eforeend() callback function, for
category/version/ example, to modify the response content-type header:
1.4.4/)

11 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/

Version 1.5 (// 1 $.ajax({


2 url: "http://fiddle.jhell.net/favicon.png",
api.jquery.com/ 3 eforeend: function( xhr ) {
category/version/ 4 xhr.overrideMimeTpe( "text/plain; charet=x-uer-de
5 }
1.5/)
6 })
7 .done(function( data ) {
Version 1.5.1 (//
8 if ( conole && conole.log ) {
api.jquery.com/ 9 conole.log( "ample of data:", data.lice(
category/version/ 10 }
11 });
1.5.1/)

Version 1.6 (//


The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the
api.jquery.com/
Promise interface, giving them all the properties, methods, and behavior
category/version/
of a Promise (see Deferred object (/category/deferred-object/) for more
1.6/)
information). These methods take one or more function arguments that
Version 1.7 (// are called when the $.ajax() request terminates. This allows you to
api.jquery.com/ assign multiple callbacks on a single request, and even to assign
category/version/ callbacks after the request may have completed. (If the request is already
1.7/) complete, the callback is fired immediately.) Available Promise methods
of the jqXHR object include:
Version 1.8 (//
api.jquery.com/
category/version/ An alternative construct to the success callback option, refer to
1.8/) deferred.done() (/deferred.done/) for implementation details.

Version 1.9 (//


api.jquery.com/
An alternative construct to the error callback option, the .fail()
category/version/
method replaces the deprecated .error() method. Refer to
1.9/) deferred.fail() (/deferred.fail/) for implementation details.
Version 1.11 & 2.1
(//api.jquery.com/
category/version/ (added in jQuery 1.6)
An alternative construct to the complete callback option, the
1.11-and-2.1/)
.alwa() method replaces the deprecated .complete()
Version 1.12 & 2.2 method.
(//api.jquery.com/
In response to a successful request, the function's arguments are
category/version/
the same as those of .done() : data, textStatus, and the jqXHR
1.12-and-2.2/) object. For failed requests the arguments are the same as those of
Version 3.0 (// .fail() : the jqXHR object, textStatus, and errorThrown. Refer to
deferred.alwa() (/deferred.alwa/) for implementation
api.jquery.com/
details.
category/version/
3.0/)

Version 3.1 (//


api.jquery.com/ Incorporates the functionality of the .done() and .fail()
category/version/ methods, allowing (as of jQuery 1.8) the underlying Promise to be
manipulated. Refer to deferred.then() (/deferred.then/) for
3.1/)
implementation details.
Version 3.2 (//

12 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/
api.jquery.com/ The jqXHR.ucce() , jqXHR.error() ,
category/version/ and jqXHR.complete() callbacks are removed as of jQuery 3.0.
3.2/) You can use jqXHR.done() , jqXHR.fail() , and
Version 3.3 (// jqXHR.alwa() instead.
api.jquery.com/
category/version/
3.3/) 1 // Aign handler immediatel after making the requet,
2 // and rememer the jqXHR oject for thi requet
Version 3.4 (// 3 var jqxhr = $.ajax( "example.php" )
api.jquery.com/ 4 .done(function() {
5 alert( "ucce" );
category/version/
6 })
3.4/) 7 .fail(function() {
8 alert( "error" );
Version 3.5 (// 9 })
api.jquery.com/ 10 .alwa(function() {
11 alert( "complete" );
category/version/ 12 });
3.5/) 13
14 // Perform other work here ...
Version 3.6 (// 15
api.jquery.com/ 16 // et another completion function for the requet aove
17 jqxhr.alwa(function() {
category/version/ 18 alert( "econd complete" );
3.6/) 19 });

Version 3.7 (//


api.jquery.com/ The thi reference within all callbacks is the object in the context
category/version/ option passed to $.ajax in the settings; if context is not specified,
3.7/) thi is a reference to the Ajax settings themselves.

For backward compatibility with XMLHttpRequet , a jqXHR object will


expose the following properties and methods:

readtate

reponeXML and/or reponeText when the underlying request


responded with xml and/or text, respectively

tatu

tatuText (may be an empty string in HTTP/2)

aort( [ tatuText ] )

getAllReponeHeader() as a string

getReponeHeader( name )

overrideMimeTpe( mimeTpe )

etRequetHeader( name, value ) which departs from the


standard by replacing the old value with the new one rather than
concatenating the new value to the old one

tatuCode( callacktatuCode )

13 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/
No onreadtatechange mechanism is provided, however, since done ,
fail , alwa , and tatuCode cover all conceivable requirements.

Callback Function Queues

The eforeend , error , dataFilter , ucce and complete options


all accept callback functions that are invoked at the appropriate times.

, the fail and done , and, as of jQuery 1.6, alwa


callback hooks are first-in, first-out managed queues, allowing for more
than one callback for each hook. See Deferred object methods (/
category/deferred-object/), which are implemented internally for these
$.ajax() callback hooks.

The callback hooks provided by $.ajax() are as follows:

1 eforeend callback option is invoked; it receives the jqXHR


object and the etting object as parameters.
2 error callback option is invoked, if the request fails. It receives
the jqXHR , 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".
3 dataFilter callback option is invoked immediately upon
successful receipt of response data. It receives the returned
data and the value of dataTpe , and must return the (possibly
altered) data to pass on to ucce .
4 ucce callback option is invoked, if the request succeeds. It
receives the returned data, a string containing the success code,
and the jqXHR object.
5 — .done() , .fail() , .alwa() , and
.then() — are invoked, in the order they are registered.
6 complete callback option fires, when the request finishes,
whether in failure or success. It receives the jqXHR object, as
well as a string containing the success or error code.

Data Types

Different types of response to $.ajax() 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 dataTpe option. If the
dataTpe option is provided, the Content-Type header of the response
will be disregarded.

The available data types are text , html , xml , jon , jonp , and
cript .

14 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/
If text or html is specified, no pre-processing occurs. The data is
simply passed on to the success handler, and made available through the
reponeText property of the jqXHR object.

If xml is specified, the response is parsed using jQuer.pareXML (/


jQuery.parseXML/) before being passed, as an XMLDocument (https://
api.jquery.com/Types/#XMLDocument), to the success handler. The XML
document is made available through the reponeXML property of the
jqXHR object.

If jon is specified, the response is parsed using jQuer.pareJON (/


jQuery.parseJSON/) before being passed, as an object, to the success
handler. The parsed JSON object is made available through the
reponeJON property of the jqXHR object.

If cript is specified, $.ajax() will execute the JavaScript that is


received from the server before passing it on to the success handler as a
string.

If jonp is specified, $.ajax() will automatically append a query string


parameter of (by default) callack=? to the URL. The jonp and
jonpCallack properties of the settings passed to $.ajax() 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.
$.ajax() will execute the returned JavaScript, calling the JSONP
callback function, before passing the JSON object contained in the
response to the $.ajax() success handler.

For more information on JSONP, see the original post detailing its use
(https://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/).

Sending Data to the Server

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 tpe option. This option affects how the contents of the data
option are sent to the server. POST data will always be transmitted to the
server using UTF-8 charset, per the W3C XMLHTTPRequest standard.

The data option can contain either a query string of the form
ke1=value1&ke2=value2 , or an object of the form {ke1: 'value1',
ke2: 'value2'} . If the latter form is used, the data is converted into a
query string using jQuer.param() (/jQuer.param/) before it is sent.
This processing can be circumvented by setting proceData to fale .
The processing might be undesirable if you wish to send an XML object
to the server; in this case, change the contentTpe option from
application/x-www-form-urlencoded to a more appropriate MIME

15 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/
type.

Advanced Options

The gloal option prevents handlers registered for the ajaxend (/


ajaxend/) , ajaxrror (/ajaxrror/) , and similar events from firing
when this request would trigger them. This can be useful to, for example,
suppress a loading indicator that was implemented with an ajaxend (/
ajaxend/) handler if the requests are frequent and brief. With cross-
domain script and JSONP requests, the global option is automatically set
to fale . See the descriptions of these methods below for more details.

If the server performs HTTP authentication before providing a response,


the user name and password pair can be sent via the uername and
paword options.

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 $.ajaxetup() (/
jQuer.ajaxetup/) rather than being overridden for specific requests
with the timeout option.

By default, requests are always issued, but the browser may serve results
out of its cache. To disallow use of the cached results, set cache to
fale . To cause the request to report failure if the asset has not been
modified since the last request, set ifModified to true .

The criptCharet allows the character set to be explicitly specified for


requests that use a <cript> tag (that is, a type of cript or jonp ).
This is useful if the script and host page have differing character sets.

The first letter in Ajax stands for "asynchronous," meaning that the
operation occurs in parallel and the order of completion is not
guaranteed. The anc option to $.ajax() defaults to true , indicating
that code execution can continue after the request is made. Setting this
option to fale (and thus making the call no longer asynchronous) is
strongly discouraged, as it can cause the browser to become
unresponsive.

The $.ajax() function returns the XMLHttpRequet 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 xhr
option. The returned object can generally be discarded, but does provide
a lower-level interface for observing and manipulating the request. In
particular, calling .aort() on the object will halt the request before it
completes.

Extending Ajax

16 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/
, jQuery's Ajax implementation includes prefilters (/
jQuery.ajaxPrefilter/), transports (/jQuery.ajaxTransport/), and converters
that allow you to extend Ajax with a great deal of flexibility.

Using Converters

$.ajax() 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
jon ), you must add a correspondence between the response Content-
Type and the actual data type using the content option:

1 $.ajaxetup({
2 content: {
3 mcutomtpe: /mcutomtpe/
4 },
5 converter: {
6 "mcutomtpe jon": function( reult ) {
7 // Do tuff
8 return newreult;
9 }
10 }
11 });

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).

To convert from a supported type (e.g text , jon ) to a custom data


type and back again, use another pass-through converter:

1 $.ajaxetup({
2 content: {
3 mcutomtpe: /mcutomtpe/
4 },
5 converter: {
6 "text mcutomtpe": true,
7 "mcutomtpe jon": function( reult ) {
8 // Do tuff
9 return newreult;
10 }
11 }
12 });

The above now allows passing from text to mcutomtpe and then
mcutomtpe to jon .

Additional Notes:
Due to browser security restrictions, most "Ajax" requests are
subject to the same origin policy (https://en.wikipedia.org/wiki/
Same_origin_policy); the request can not successfully retrieve data
from a different domain, subdomain, port, or protocol.

17 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/
Script and JSONP requests are not subject to the same origin
policy restrictions.

Examples:
Save some data to the server and notify the user once it's complete.

1 $.ajax({
2 method: "POT",
3 url: "ome.php",
4 data: { name: "John", location: "oton" }
5 })
6 .done(function( mg ) {
7 alert( "Data aved: " + mg );
8 });

Retrieve the latest version of an HTML page.

1 $.ajax({
2 url: "tet.html",
3 cache: fale
4 })
5 .done(function( html ) {
6 $( "#reult" ).append( html );
7 });

Send an xml document as data to the server. By setting the processData


option to fale , the automatic conversion of data to strings is
prevented.

1 var xmlDocument = [create xml document];


2 var xmlRequet = $.ajax({
3 url: "page.php",
4 proceData: fale,
5 data: xmlDocument
6 });
7
8 xmlRequet.done( handleRepone );

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.

18 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/
1 var menuId = $( "ul.nav" ).firt().attr( "id" );
2 var requet = $.ajax({
3 url: "cript.php",
4 method: "POT",
5 data: { id : menuId },
6 dataTpe: "html"
7 });
8
9 requet.done(function( mg ) {
10 $( "#log" ).html( mg );
11 });
12
13 requet.fail(function( jqXHR, texttatu ) {
14 alert( "Requet failed: " + texttatu );
15 });

Load and execute a JavaScript file.

1 $.ajax({
2 method: "GT",
3 url: "tet.j",
4 dataTpe: "cript"
5 });

BOOKS

Learning jQuery jQuery in Action jQuery Succinctly


Fourth Edition Bear Bibeault, Yehuda Cody Lindley
Karl Swedberg and Katz, and Aurelio De (https://
Jonathan Chaffer Rosa www.syncfusion.com/
(https:// (https:// ebooks/jquery)
www.packtpub.com/ www.manning.com/
web-development/ books/jquery-in-
learning-jquery- action-third-edition)
fourth-edition)

Copyright 2023 OpenJS Foundation (https://openjsf.org/) and


jQuery contributors. All rights reserved. See jQuery License
 Learning Center (https://learn.jquery.com/)
(https://jquery.org/license/) for more information. The
OpenJS Foundation (https://openjsf.org/) has registered  Forum (https://forum.jquery.com/)
trademarks and uses trademarks. For a list of trademarks of
the OpenJS Foundation (https://openjsf.org/), please see our  Twitter (https://twitter.com/jquery)
Trademark Policy (https://trademark-policy.openjsf.org/) and
Trademark List (https://trademark-list.openjsf.org/).  IRC (https://irc.jquery.org/)
Trademarks and logos not indicated on the list of OpenJS
Foundation trademarks (https://trademark-list.openjsf.org/)
are trademarks™ or registered® trademarks of their
 GitHub (https://github.com/jquery)
respective holders. Use of them does not imply any affiliation
with or endorsement by them. OpenJS Foundation Terms of

19 of 20 9/10/23, 22:31
jQuery.ajax() | jQuery API Documentation http://api.jquery.com/jquery.ajax/
Use (https://terms-of-use.openjsf.org/), Privacy (https://
privacy-policy.openjsf.org/), and Cookie (https://
www.linuxfoundation.org/cookies) Policies also apply.

Web hosting by Digital Ocean (https://www.digitalocean.com) |


CDN by StackPath (https://www.stackpath.com)

20 of 20 9/10/23, 22:31

You might also like