jQuery.ajax()S2C Home « Ajax « jQuery.ajax()

Asynchronous HTTP (Ajax) request.

Description

The jQuery.ajax() Ajax method, allows us to perform an asynchronous HTTP (Ajax) request.

Shorthand version $.ajax()

  • The jQuery.ajax() method underpins any Ajax requests sent by jQuery and comes with a plethora of settings, giving us a great deal of flexibility when making our requests. There are other jQuery Ajax methods such as jQuery.get() and jQuery.post() which are easier to use for general purpose requests.
  • Browsers operate the 'same origin policy', which means a request can not successfully retrieve data from a different domain, subdomain, or protocol. jQuery 'Ajax' requests are subject to this security restriction, the exceptions being requests made with a datatype of 'script' or 'jsonp'.
  • The jQuery.ajax() method returns a jqXHR object which is a superset of the browser's native XMLHttpRequest object. The jqXHR object implements the Promise interface, giving it all the properties, methods, and behavior of a Promise. See the lesson on the Deferred object for details of this. For standardization with the the Deferred object, the jqXHR object also provides done(), fail() and always() methods. These methods take a function argument that is called when the jQuery.ajax() request terminates and the function receives the same arguments as the same-named success(), error() and complete() setting callbacks respectively. This allows assignment of multiple callbacks for a single request as well as assigning callbacks after the request has completed. For completed requests, the callback is fired immediately.
  • It should be noted that success(), error() and complete() callbacks were deprecated from use on request completion from jQuery 1.8 and removed in jQuery 3.0. This is for completion processing only and the Ajax settings will still have these values. Best practice is to use done(), fail() and always() methods on request completion to future proof code.
  • A jqXHR object will expose the following properties and methods for backward compatibility with the XMLHttpRequest object:

jqXHR Object Description
Methods
abort()Cancels the currently executing request.
getAllResponseHeaders()Returns a string containing the names and value of all response headers.
getResponseHeader(name)Returns the value of the specified response headers.
.overrideMimeType()Used in the beforeSend() callback function, to modify the response content-type header.
setRequestHeader(name, value)Set a request header using the specified name and value.
Properties
readyStateAn integer indicating the current state of the request.
responseTextUnderlying request responded with text.
responseXMLUnderlying request responded with xml.
statusResponse status code returned from the server.
statusTextStatus text message returned by the response.

Syntax

Signature Description
jQuery.ajax( url [, settings] )Perform an asynchronous HTTP (Ajax) request to be sent to the specified url, optionally passing some request settings.
jQuery.ajax( settings )Perform an asynchronous HTTP (Ajax) request, optionally passing some request settings.

Parameters

Parameter Description
url A string containing the URL to send the request to.
settings Default settings can be set globally by using the jQuery.ajaxSetup() method but the settings below can be useful for individual Ajax requests.

Optional set of key/value pairs that configure the Ajax request.
  • acceptsPlainObject
    Default: depends on DataType
    The content type sent in the request header which informs the server what kind of response it will accept on return.
  • asyncBoolean
    Default: true
    If you need synchronous requests this can be achieved by setting this option to false:
    • Synchronous requests by their nature may lock the browser, temporarily disabling any actions while the request is active.
    • Cross-domain requests and requests using the jsonp dataType do not support synchronous operation.
    • From jQuery version 1.8, using async: false is deprecated, so best to avoid using this setting altogether and let it default.
  • beforeSend(jqXHR, settings)Function
    A pre-request callback function that can be used to modify the jqXHR and will be called regardless of the type of request:
    • The jqXHR object and settings s are passed as arguments.
    • if the beforeSend() function returns false it will cancel the $.ajax()request.
    • Use this to set customized headers and such.
    • This is an Ajax Event.
  • cacheBoolean
    Default: false for dataType jsonp and script | true for all other dataType
    When set to false:
    • Requested pages will not be cached by the browser.
    • Appends a query string parameter, "_=[TIMESTAMP]", to the URL.
  • complete(jqXHR, textStatus)Function(s)
    A function or an array of functions, where each function gets called in turn, to be called when success and fail callbacks have executed and the request has finished:
    • The jqXHR object and a string categorizing the status of the request ( "abort", "error", "notmodified", "parsererror", "success" or "timeout") are passed as arguments.
    • This is an Ajax Event.
    • This is callback hook which is a first-in, first-out managed queue and as such can assign more than one callback for each hook. See the lesson on the Deferred object and methods, which are implemented internally for these jQuery.ajax() callback hooks, for an explanation of the mechanics and how to use deferreds.
    • When the request finishes 'completeCallbacks' fire in the order they were registered, whether 'error' or 'success'.
  • contentsPlainObject
    An object of string/regular-expression pairs determining how jQuery will parse the response, given its content type.
  • content-typeString
    Default: 'application/x-www-form-urlencoded'
    Sets the content type for data being sent to the server and the default is fine for most situations:
    • If you explicitly pass in content-type to the $.ajax() method it will always be sent to the server, regardless of any data being sent.
    • Data is always transmitted to the server using the UTF-8 charset and you must decode this appropriately on the server side.
  • contextObject
    An object to be made the context for all Ajax-related callbacks:
    • By default, the context is an object representing any ajax settings passed to the jQuery.ajax method merged with those setup from the jQuery.ajaxSetup() method.
  • convertersPlainObject
    Default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML())
    An object of dataType-to-dataType converters.
    • Each converter's value is a function that returns the transformed value of the response.
  • crossDomainBoolean
    Default: false for same-domain requests | true for cross-domain requests.
    • If you wish to force a crossDomain request on the same domain, set the value of crossDomain to true.
  • dataObject or String
    Data to be sent to the server:
    • For objects, the object must consist of Key/Value pairs. If the value is an array, jQuery will serialize multiple values with the same key based on the value of the traditional setting which is described below for that setting. This processing can be circumvented by setting the processData option to false. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type.
    • For anything else, if not already a string the data gets converted to a query string and is appended to the url for GET-requests. This processing can be circumvented by setting the processData option to false.
  • dataFilter(data, type)Function
    Function used to handle the raw response data of a XMLHttpRequest:
    • The function accepts two arguments, the raw data as returned from the server and the dataType parameter.
    • This is a pre-filtering function to sanitize the response and the sanitized data will be passed on to the
      done(data, textStatus, jqXHR) callback function.
  • dataTypeString
    Default: Inferred based on the MIME type of the response (html, json, script, or xml)
    A string value or multiple, space-separated string values specifying the type of data that you're expecting back from the server.
    Ensure that the MIME type reported by the web server matches your choice of dataType.
    The jQuery.ajax() method relies on the server to provide information about the retrieved data. If the server reports the return data as XML, the result can be traversed using normal XML methods or jQuery's selectors. If another type is detected the data is treated as text but different data handling can be achieved using the dataType settings as outlined below:

    • "html": Returns HTML as a plain text string after executing any embedded JavaScript inside the retrieved data.
    • "json": Evaluates the response as JSON and returns a JavaScript object as the result data. This is achieved using the jQuery.parseJSON() method when the browser supports it or a Function constructor otherwise. Malformed JSON data will throw a parse error as detailed here: json.org site.
      If the fetched data file exists on a remote server, specify the jsonp type instead.
    • "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of the URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. The server should prepend the JSON data with the callback name to form a valid JSONP response. We can specify a parameter name other than callback when using the jQuery.ajax() method by using the jsonp setting as described under the setting parameters below.
      JSONP is an extension of the JSON format, requiring some server-side code to detect and handle the query string parameter. When data is retrieved from remote servers, any error callbacks and global events will never be fired.
    • "script": Executes the JavaScript that is pulled back from the server and then returns nothing. From jQuery 3.0 When requesting a script on a domain other than the one that hosts the document, you must now explicitly specify dataType: "script" in the options when using jQuery.ajax() to prevent cross domain attacks.
      When data is retrieved from remote servers, any error callbacks and global events will never be fired.
    • "text": Returns a plain text string with no processing. The data is simply passed on to the success handler through the responseText property of the jqXHR object.
    • xml": Returns a XML document with no processing that can be processed via jQuery. The data is simply passed on to the success handler through the responseXML property of the jqXHR object.
      XML must be declared by the server as text/xml or application/xml for consistent results.
    • Multiple space-separated string values will notify a value to receive and how that value is intepreted. For example "jsonp text xml" equates to make a JSONP request, have it received as text, and interpreted by jQuery as XML.
  • error(jqXHR, textStatus, errorThrown)Function(s)
    A function or an array of functions, where each function gets called in turn:
    • The jqXHR object, a string categorizing the status of the request ( "abort", "error", "null", "parsererror", "success" or "timeout") and an optional exception object, if one occurred, are passed as arguments.
    • This handler is not called for cross-domain script and jsonp requests.
    • This is an Ajax Event.
    • This is callback hook which is a first-in, first-out managed queue and as such can assign more than one callback for each hook. See the lesson on the Deferred object and methods, which are implemented internally for these jQuery.ajax() callback hooks, for an explanation of the mechanics and how to use deferreds.
    • When the request finishes 'errorCallbacks' fire in the order they were registered.
  • globalBoolean
    Default: true
    Whether to trigger global Ajax event handlers for this request.
    • Setting this to false will prevent the global Ajax event handlers from triggering for this request.
  • headersPlainObject
    Default: {}
    An object of additional header key/value pairs to send along with the request:
    • Set before the beforeSend() function is called and so any values modified with this setting can be overwritten from within the beforeSend() function.
  • ifModifiedBoolean
    Default: false
    • Setting this to true will check the Last-Modified header to see if the asset has been modified since the last request.
  • isLocalBoolean
    Default: dependant upon current location protocol
    Allow the current environment (the filesystem) to be recognized as "local," even if jQuery doesn't recognize it as such by default.
    • The following protocols are currently recognized as local: file, *-extension, and widget.
    • If the isLocal setting needs modifying, do this once in the jQuery.ajaxSetup() method.
  • jsonpString
    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.
    • Setting the jsonp option to false prevents jQuery from adding the 'callback=?' string to the URL or attempting to use "=?" for transformation. In this scenario, the jsonpCallback setting should also be explicitly set. For example, { jsonp: false, jsonpCallback: "callbackName" }.
  • jsonpCallbackString or Function
    Specify the callback function name for a jsonp request:
    • This value will be used instead of the random name automatically generated by jQuery although it is preferable to let jQuery generate a unique name to make it easier to manage the requests, provide callbacks and error handling.
    • You may want to specify the callback name using jsonpCallback when you want to enable better browser caching of GET requests.
    • If you use a function to set the value of jsonpCallback, it will be set to the return value of that function.
  • mimeTypeString
    A mime type to override the XHR mime type.
  • passwordString
    A password to be used in response to an HTTP access authentication request.
    If the server performs HTTP authentication before providing a response, the user name and password pair can be sent via the username and password options.
  • processDataBoolean
    Default: true
    By default, data passed in to the data 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".
    • Setting this option to false allows sending of a DOMDocument, or other non-processed data.
  • scriptCharsetString
    Forces the request to be interpreted as a certain charset:
    • Only pertinent for requests with "jsonp" or "script" dataType and "GET" type.
    • Only required for charset differences between the remote and local content.
  • statusCodePlainObject
    Default: {}
    An object of numeric HTTP codes and functions to be called when the response has the corresponding code:
    • If the request is successful, the status code functions take the same parameters as the done callback.
    • If the request fails, the status code functions take the same parameters as the fail callback.
  • success(data, textStatus, jqXHR)Function(s)
    A function or an array of functions, where each function gets called in turn, that is called if the request succeeds:
    • The function gets passed three arguments, the data returned from the server formatted according to the dataType parameter, a string describing the status and the jqXHR object.
    • This is an Ajax Event.
    • This is callback hook which is a first-in, first-out managed queue and as such can assign more than one callback for each hook. See the lesson on the Deferred object and methods, which are implemented internally for these jQuery.ajax() callback hooks, for an explanation of the mechanics and how to use deferreds.
    • When the request finishes 'successCallbacks' fire in the order they were registered.
  • timeoutNumber
    Set a timeout (in milliseconds) for the request:
    • The timeout period starts at the point when the jQuery.ajax call is made and in certain scenarios it is possible for a request to time out before it can be sent.
    • Using the timeout setting will override any global timeout set with the jQuery.ajaxSetup() method, but this is not recommended for specific requests.
  • traditionalBoolean
    Set this to true if you wish to use the traditional style of param serialization as used by the
    jQuery.param( obj, traditional ) method signature.
  • typeString
    Default: 'GET'
    The type of request to make ('POST' or 'GET'):
    • Ajax requests default to being sent using the 'GET' HTTP method. If the 'POST' method is required, this can be specified by setting a value using the type setting. The type setting 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, as per the W3C XMLHTTPRequest standard.
    • Other HTTP request methods besides 'POST' and 'GET' can also be used, but are not supported in all browsers.
  • urlString
    Default: The current page
    A string containing the URL to which the request is to be sent.
  • usernameString
    A password to be used in response to an HTTP access authentication request.
    If the server performs HTTP authentication before providing a response, the user name and password pair can be sent via the username and password options.
  • xhrString
    Default: ActiveXObject when available (IE), the XMLHttpRequest otherwise
    Callback for creating the ActiveXObject / XMLHttpRequest object:
    • Override to provide your own implementation for ActiveXObject / XMLHttpRequest or enhancements to the factory.
  • xhrFieldsPlainObject
    An object of fieldName-fieldValue pairs to set on the native XHR object.

Return

A Promise object which is just a copy of a Deferred object without any notify/resolve/reject methods.


jQuery.ajax( url [, settings] ) ExamplesTop

Perform an asynchronous HTTP (Ajax) request to be sent to the specified url, optionally passing some request settings.

In the example below when we press the left button the first time, we create an Ajax request, passing the datatype along with the error() callback function. For this example the request will fail as the 'get11.js' asset does not exist. Therefore the error() callback setting activates and outputs a message.

In the example below when we press the right button the first time, we create an Ajax request, passing the datatype along with the success() callback function. For this example the request will succeed as the 'get1.js' asset does exist. Therefore the script for the 'get1.js' asset executes as we have passed across a datatype of 'script'. After this the success() callback setting activates and outputs a message telling us the request succeeded.


$(function(){
  $('#btn1').one('click', function(){
    $.ajax( "../js/get11.js", {
      dataType: "script",
      error: function() { 
        $('#div1').append('The request failed! <br><br>');
      }
    });
  });
  $('#btn2').one('click', function(){
    $.ajax( "../js/get1.js", {
      dataType: "script",
      success: function() { 
        $('#div1').append('The request was a sucesss! <br><br>');
      }
    });
  });
});

/*
 * The code for the external Javascript file called from $.ajax() (url: "../js/get1.js")
 * is shown below.
 */
$(function(){
  var someText = 'Passing some text. ';
  $('#div1').append('Message from get1.js: ' + someText + '<br>');
});

div1. Some initial text.

Press the button below to action the above code:

               



jQuery.ajax( settings ) ExamplesTop

Perform an asynchronous HTTP (Ajax) request, optionally passing some request settings.

In the example below when we press the left button the first time, we create an Ajax request for a 'GET', passing some settings across. The settings include the url, the type and datatype along with some callback functions which output some messages. The beforeSend() callback setting always gets called and we output a message about the asset we are calling. For this example the request will fail as the 'get22.js' asset does not exist. Therefore the error() callback setting activates and outputs a message telling us the request failed. The complete() callback setting always fires regardless of success or failure and so also outputs a message.

In the example below when we press the right button the first time, we create an Ajax request for a 'GET', passing some settings across. The settings include the url, the type and datatype along with some callback functions which output some messages. The beforeSend() callback setting always gets called and we output a message about the asset we are calling. For this example the request will succeed as the 'get2.js' asset does exist. Therefore the script for the 'get1.js' asset executes as we have passed across a datatype of 'script'. After this the success() callback setting activates and outputs a message telling us the request succeeded. The complete() callback setting always fires regardless of success or failure and so also outputs a message.


$(function(){
  $('#btn3').one('click', function(){
    $.ajax({
      beforeSend: function() { 
        $('#div2').append('About to call the get22.js asset <br>');
      },
      type: "GET",
      url: "../js/get22.js",
      dataType: "script",
      success: function() { 
        $('#div2').append('The request was a sucesss! <br>');
      },
      error: function() { 
        $('#div2').append('The request failed! <br>');
      },
      complete: function() { 
        $('#div2').append('The request completed! <br><br>');
      }
    });
  });
  $('#btn4').one('click', function(){
    $.ajax({
      beforeSend: function() { 
        $('#div2').append('About to call the get2.js asset <br>');
      },
      type: "GET",
      url: "../js/get2.js",
      dataType: "script",
      success: function() { 
        $('#div2').append('The request was a sucesss! <br>');
      },
      error: function() { 
        $('#div2').append('The request failed! <br>');
      },
      complete: function() { 
        $('#div2').append('The request completed! <br><br>');
      }
    });
  });
});

/*
 * The code for the external Javascript file called from $.ajax() (url: "../js/get2.js")
 * is shown below.
 */
$(function(){
  var someText = 'Some text to pass across ';
  $('#div2').append('Message from get2.js: ' + someText + '
'); });

div2. Some initial text.

Press the button below to action the above code: